Backups, index care and health checks must happen every night, whether you are at your desk or not. This guide shows how to let SQL Server Agent do the work: create a job with a step and a schedule in T-SQL, run it and read its history, get an email when it fails with an operator, react to problems with alerts, and run the usual maintenance: backups, index REORGANIZE and REBUILD, DBCC CHECKDB and statistics.
Part of the SQL Server for Beginners series. This article is the written version of lesson 14 of the Bigland Network video course, with the same sample data. The job examples were run on a test instance with SQL Server Agent running; run every example on a test server, not on production. SQL Server Agent is not available in the Express edition or in LocalDB.
Watch lesson 14 as a video or open it on YouTube. The written lesson below follows the same steps and the same sample data.
Contents
- 1. What is SQL Server Agent?
- 2. The anatomy of a job
- 3. Create a job, a step and a schedule
- 4. Run the job and read the history
- 5. Operators and alerts
- 6. The usual maintenance jobs
- 7. Index fragmentation: reorganize or rebuild
- 8. DBCC CHECKDB
- 9. Maintenance plans or scripts
- 10. Mistakes and best practices
- 11. Practice
1. What is SQL Server Agent?
- A service: a Windows service that runs scheduled work for SQL Server.
- A job: a named list of steps, such as a backup or an index rebuild.
- msdb: the system database where jobs and their history are stored.
- Editions: not in Express or LocalDB. Standard edition and above have it.
In SQL Server Management Studio, SQL Server Agent sits at the bottom of the server tree in Object Explorer. A green icon means the service runs, a red one means it is stopped. Right-click Jobs then New Job to use the dialog, or right-click a job to start it or view its history.
2. The anatomy of a job
A schedule starts the job. The job runs its steps in order, for example step 1 backs up the database and step 2 checks the backup. At the end it can notify an operator by email. Each step also says what happens next: go to the next step, quit with success, or quit with failure.
3. Create a job, a step and a schedule
The dialog is nice, but T-SQL is repeatable. Four procedures in msdb do the work. First the job, and a query that shows it:
EXEC msdb.dbo.sp_add_job @job_name = N'Nightly Backup';
SELECT name, enabled FROM msdb.dbo.sysjobs
WHERE name = N'Nightly Backup';
| name | enabled |
|---|---|
| Nightly Backup | 1 |
Then the step. It runs a stored procedure (see lesson 6) that does the backup:
EXEC msdb.dbo.sp_add_jobstep
@job_name = N'Nightly Backup',
@step_name = N'Run backup',
@subsystem = N'TSQL',
@command = N'EXEC dbo.usp_BackupCompanyDB;',
@database_name = N'BiglandDemo';
| step_id | step_name | subsystem |
|---|---|---|
| 1 | Run backup | TSQL |
Now the schedule:
EXEC msdb.dbo.sp_add_jobschedule
@job_name = N'Nightly Backup',
@name = N'Every night at 2 AM',
@freq_type = 4, @freq_interval = 1,
@active_start_time = 20000;
| name | freq_type | freq_interval | active_start_time |
|---|---|---|---|
| Every night at 2 AM | 4 | 1 | 20000 |
The numbers: freq_type 1 is once, 4 is daily, 8 is weekly and 16 is monthly. freq_interval 1 with type 4 means every 1 day. active_start_time uses the hhmmss format, so 20000 is 02:00:00 and 233000 is 23:30:00. Finally attach the job to this server. This is the step people forget, and without it the job never runs:
EXEC msdb.dbo.sp_add_jobserver
@job_name = N'Nightly Backup';
4. Run the job and read the history
Never trust a new job before you test it by hand:
EXEC msdb.dbo.sp_start_job
@job_name = N'Nightly Backup';
WAITFOR DELAY '00:00:10';
SELECT j.name, s.last_run_outcome
FROM msdb.dbo.sysjobs j
JOIN msdb.dbo.sysjobservers s ON s.job_id = j.job_id
WHERE j.name = N'Nightly Backup';
| name | last_run_outcome |
|---|---|
| Nightly Backup | 1 |
sp_start_job returns at once while the job keeps running; outcome 1 means it succeeded. The history lives in msdb.dbo.sysjobhistory. Rows with step_id = 0 are the outcome of the whole job, and run_status is 1 for succeeded and 0 for failed:
SELECT j.name, h.step_id, h.run_status, h.message
FROM msdb.dbo.sysjobs j
JOIN msdb.dbo.sysjobhistory h
ON h.job_id = j.job_id
WHERE h.step_id = 0;
In the video test, Nightly Backup shows run_status 1 (the job succeeded) and a deliberately broken test job, whose step calls a procedure that does not exist, shows run_status 0 (the job failed). To list only the failures, filter on h.run_status = 0.
5. Operators and alerts
Looking at history by hand is not enough. Create an operator and tell the job to notify it when it fails (real emails need Database Mail to be set up):
EXEC msdb.dbo.sp_add_operator
@name = N'DBA Team',
@email_address = N'dba@example.com';
EXEC msdb.dbo.sp_update_job
@job_name = N'Nightly Backup',
@notify_level_email = 2,
@notify_email_operator_name = N'DBA Team';
Level 2 means on failure. An unwatched failure is the worst failure. Alerts react to problems: an alert watches for an error number, a severity or a performance counter, and can run a job or notify an operator. Examples: errors with severity 19 to 25 email the team at once, and a transaction log that is 90 percent full starts a log backup job.
6. The usual maintenance jobs
- Backups: full, differential and log backups (lesson 12).
- Indexes: reorganize or rebuild the fragmented ones.
- Statistics: update them so plans stay good (lesson 13).
- CHECKDB: check the database for corruption, every week.
- Cleanup: delete old backups and old job history.
7. Index fragmentation: reorganize or rebuild
Indexes get fragmented as data changes, like a bookshelf where the books are put back in random order. Rules of thumb, not laws:
| Fragmentation | Action |
|---|---|
| Below 5 percent | Nothing to do |
| 5 to 30 percent | REORGANIZE: light, can stop any time |
| Above 30 percent | REBUILD: heavier, makes a fresh index |
SELECT i.name, s.avg_fragmentation_in_percent
FROM sys.dm_db_index_physical_stats
(DB_ID(), OBJECT_ID(N'dbo.Employees'),
NULL, NULL, 'LIMITED') s
JOIN sys.indexes i
ON i.object_id = s.object_id AND i.index_id = s.index_id;
On our tiny test table every index shows 0 percent, and for a table with six employees nobody cares. Then, for the middle range or the high range:
ALTER INDEX IX_Emp_Salary ON Employees REORGANIZE;
ALTER INDEX IX_Emp_Salary ON Employees REBUILD;
Do not rebuild every index every night: check first, and only treat big indexes that need it.
8. DBCC CHECKDB
DBCC CHECKDB (BiglandDemo) WITH NO_INFOMSGS;
It reads everything and looks for corruption. With NO_INFOMSGS, no output at all (just “Commands completed successfully”) means no problems were found. Run it weekly, in a job, at a quiet time. If corruption appears early, you still have good backups to restore from.
9. Maintenance plans or scripts
- Maintenance Plan wizard: in SSMS under Management. Quick, point and click.
- Community scripts: free scripts such as the ones from Ola Hallengren are popular and flexible.
- Either way, they end up as Agent jobs that you schedule and monitor.
10. Mistakes and best practices
- Creating a job and never testing it by hand.
- No notification, so failures stay silent.
- Rebuilding every index every night.
- Forgetting
sp_add_jobserver. - A stopped Agent service that nobody notices.
- Best practice: give jobs clear names and a description, always set a failure notification to an operator, do not overlap heavy jobs (backups and rebuilds should not fight for the same disk), keep the step code in stored procedures, and check the history and restore a backup now and then, because a backup you never restored is just a nice hope.
One practical note from the test server: if a job fails with “Unable to determine if the owner is a member of the sysadmin role”, the job owner is an account that Agent cannot validate. Set a valid owner with sp_update_job @owner_login_name.
11. Practice
- Which
freq_typeandactive_start_timerun a job daily at 11:30 PM? - An index shows 12 percent fragmentation, another shows 45. What do you do?
- Write a query that lists failed job runs:
run_status = 0, fromsysjobhistory.
-- 1: daily at 11:30 PM
@freq_type = 4, @freq_interval = 1, @active_start_time = 233000
-- 2: 12 percent = REORGANIZE, 45 percent = REBUILD
ALTER INDEX IX_Emp_Salary ON Employees REORGANIZE;
ALTER INDEX IX_Emp_Salary ON Employees REBUILD;
-- 3: failed runs
SELECT j.name, h.run_date, h.run_time, h.message
FROM msdb.dbo.sysjobs j
JOIN msdb.dbo.sysjobhistory h ON h.job_id = j.job_id
WHERE h.run_status = 0;
Frequently asked questions
Why is my SQL Server Agent job not running?
Check that the Agent service is running, that the job is enabled, that it has a schedule, and that you attached it to the server with sp_add_jobserver. Then read the job history for the error message.
Can I use SQL Server Agent in Express edition?
No. Express and LocalDB do not run Agent jobs. Use Standard edition or above, or schedule the T-SQL with Windows Task Scheduler and sqlcmd.
Should I reorganize or rebuild an index?
As a rule of thumb, reorganize between 5 and 30 percent fragmentation and rebuild above 30 percent, and only for indexes big enough to matter.
What to learn next
The next lesson, Lesson 15: Encryption and Auditing Basics, covers encryption and auditing: hashing, masking, TDE and SQL Server Audit. See also SQL Server Agent Jobs for a wider guide. Previous lesson: Lesson 13: Query Performance Tuning.
The whole series
- Lesson 1: SELECT, WHERE and ORDER BY
- Lesson 2: JOINs
- Lesson 3: GROUP BY, HAVING and Subqueries
- Lesson 4: INSERT, UPDATE, DELETE and Transactions
- Lesson 5: CREATE TABLE, Data Types and Constraints
- Lesson 6: Indexes, Views and Stored Procedures
- Lesson 7: CTEs and Window Functions
- Lesson 8: Built-in Functions
- Lesson 9: Functions, Temp Tables and Table Variables
- Lesson 10: Triggers and Audit Tables
- Lesson 11: Security: Logins, Users and Roles
- Lesson 12: Backup, Restore and Recovery Models
- Lesson 13: Query Performance Tuning
- Lesson 14: SQL Server Agent Jobs and Maintenance (this article)
- Lesson 15: Encryption and Auditing Basics
- Lesson 16: Working with JSON
- Lesson 17: Temporal Tables and Row History
- Lesson 18: Partitioning and Large Tables
- lesson 19: Full Text Search
- lesson 20: Query Store and Slow Queries
Sources and further reading
- Microsoft Learn, Transact-SQL reference (Database Engine), on learn.microsoft.com: the official syntax for the statements used here.
- Microsoft Learn, SQL Server Agent and sp_add_job (Transact-SQL), for the job, step and schedule procedures in msdb.
More tutorials like this
Msg 208 Invalid Object Name in SQL Server: Causes and Fix
Fix SQL Server Msg 208 Invalid object name: check the spelling, the database and the schema, with real SSMS examples and scripts to find…
SQL Server Query Store Tutorial: Find Slow Queries, Compare Plans and Force a Plan
Turn on Query Store, find the most expensive queries with the sys.query_store views and the SSMS reports, compare the plans of one query and…
SQL Server Full Text Search Tutorial: CONTAINS, FORMSOF and CONTAINSTABLE
Search words inside text columns fast: create a full text catalog and index, use CONTAINS, word forms, phrases and rank the best matches with…
