A trigger is code that runs by itself when data changes. This guide shows how to build an audit table, write AFTER and INSTEAD OF triggers, use the special inserted and deleted tables, and manage triggers safely, so you always know who changed what, and when.
Part of the SQL Server for Beginners series. This article is the written version of lesson 10 of the Bigland Network video course, with the same sample data. The results shown were worked out by hand from that data, so run every example on a test database, not on production data.
Watch lesson 10 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 a trigger?
- 2. An audit table and your first trigger
- 3. The inserted and deleted tables
- 4. Testing: one row and many rows
- 5. Archive deleted rows
- 6. INSTEAD OF triggers and rules
- 7. Who, when and managing triggers
- 8. Mistakes and best practices
- 9. Practice
1. What is a trigger?
- A trigger is code attached to a table that runs automatically on
INSERT,UPDATEorDELETE. - The classic use is auditing: keeping a history of changes.
- You never call a trigger yourself. SQL Server fires it for you.
| Kind | Notes |
|---|---|
| AFTER | Runs after the change succeeded. Best for audit. |
| INSTEAD OF | Runs in place of the change. You decide what happens. |
| DDL | Fires on CREATE, ALTER or DROP, to watch the schema. |
| LOGON | Fires when someone connects to the server. |
2. An audit table and your first trigger
First, a normal table that will receive the history. The date and time fill themselves in:
CREATE TABLE SalaryAudit (
AuditId INT IDENTITY(1,1) PRIMARY KEY,
EmpId INT,
OldSalary INT,
NewSalary INT,
ChangedAt DATETIME2 DEFAULT GETDATE()
);
Then the trigger. AFTER UPDATE means it runs after every update on Employees:
CREATE TRIGGER trg_Emp_Update
ON Employees AFTER UPDATE
AS
BEGIN
SET NOCOUNT ON;
INSERT INTO SalaryAudit (EmpId, OldSalary, NewSalary)
SELECT i.Id, d.Salary, i.Salary
FROM inserted i JOIN deleted d ON i.Id = d.Id;
END;
3. The inserted and deleted tables
| Table | Contains |
|---|---|
| inserted | The NEW version of the rows |
| deleted | The OLD version of the rows |
| After INSERT | Only inserted has rows |
| After DELETE | Only deleted has rows |
| After UPDATE | Both: old values in deleted, new values in inserted |
They exist only while the trigger runs, which is why we join them on the Id.
4. Testing: one row and many rows
UPDATE Employees SET Salary = 4400
WHERE Id = 1;
SELECT EmpId, OldSalary, NewSalary
FROM SalaryAudit;
| EmpId | OldSalary | NewSalary |
|---|---|---|
| 1 | 4200 | 4400 |
One statement can change many rows. The trigger runs once and handles all of them, because it uses set based code:
UPDATE Employees SET Salary = Salary + 100
WHERE DeptId = 2;
SELECT EmpId, OldSalary, NewSalary
FROM SalaryAudit ORDER BY EmpId;
| EmpId | OldSalary | NewSalary |
|---|---|---|
| 1 | 4200 | 4400 |
| 2 | 5200 | 5300 |
| 5 | 4800 | 4900 |
Log only real changes
CREATE OR ALTER TRIGGER trg_Emp_Update
ON Employees AFTER UPDATE
AS
BEGIN
SET NOCOUNT ON;
IF NOT UPDATE(Salary) RETURN;
INSERT INTO SalaryAudit (EmpId, OldSalary, NewSalary)
SELECT i.Id, d.Salary, i.Salary
FROM inserted i JOIN deleted d ON i.Id = d.Id
WHERE i.Salary <> d.Salary;
END;
Now UPDATE Employees SET Salary = Salary WHERE Id = 3; writes nothing, so SELECT COUNT(*) AS AuditRows FROM SalaryAudit; still returns 3.
5. Archive deleted rows
CREATE TRIGGER trg_Emp_Delete
ON Employees AFTER DELETE
AS
INSERT INTO EmpArchive (Id, FirstName, DeptId, Salary)
SELECT Id, FirstName, DeptId, Salary FROM deleted;
GO
DELETE FROM Employees WHERE Id = 6;
SELECT * FROM EmpArchive;
| Id | FirstName | DeptId | Salary |
|---|---|---|---|
| 6 | Omar | NULL | 3900 |
6. INSTEAD OF triggers and rules
An INSTEAD OF trigger replaces the change. This one blocks deleting accounts:
CREATE TRIGGER trg_NoDelete
ON Accounts INSTEAD OF DELETE
AS
BEGIN
THROW 50001, 'Accounts cannot be deleted.', 1;
END;
GO
DELETE FROM Accounts WHERE Id = 1;
The result is error 50001, “Accounts cannot be deleted.”, and the row stays in the table.
A trigger can also enforce a rule and undo the change with ROLLBACK:
CREATE TRIGGER trg_Salary_Positive
ON Employees AFTER UPDATE
AS
BEGIN
IF EXISTS (SELECT 1 FROM inserted WHERE Salary < 0)
BEGIN
ROLLBACK TRANSACTION;
THROW 50002, 'Salary cannot be negative.', 1;
END
END;
If a simple CHECK constraint can do the job, use the constraint instead: it is faster and easier to understand.
7. Who, when and managing triggers
| Function | Returns |
|---|---|
| GETDATE() | The date and time of the change |
| SUSER_SNAME() | The login name of the person |
| HOST_NAME() | The name of the computer |
| APP_NAME() | The application used, such as SSMS |
SELECT name FROM sys.triggers;
DISABLE TRIGGER trg_Emp_Update ON Employees;
ENABLE TRIGGER trg_Emp_Update ON Employees;
DROP TRIGGER IF EXISTS trg_Emp_Update;
Disable a trigger during a big import, but always enable it again. While it is off, changes are not recorded.
You do not always need a trigger. The OUTPUT clause shows a change right away:
UPDATE Employees SET Salary = Salary + 50
OUTPUT inserted.Id, deleted.Salary AS OldSal,
inserted.Salary AS NewSal
WHERE Id = 4;
| Id | OldSal | NewSal |
|---|---|---|
| 4 | 3100 | 3150 |
8. Common mistakes and best practices
- Writing a trigger as if it handled one row: a statement can change many rows.
- Putting slow code in a trigger. It slows every change (How to Find and Fix Slow Queries in SQL Server).
- Forgetting that triggers are hidden: other people will not expect them.
- Using a trigger when a
CHECKconstraint is enough. - Disabling a trigger and never enabling it again.
- Best practice: use set based code with
insertedanddeleted, keep triggers short, use constraints first, use clear names such astrg_Emp_Update, and store who, what and when in the audit table.
9. Practice
- Create HireLog and an AFTER INSERT trigger that saves each new first name. Add Layla.
- Block deleting departments with an INSTEAD OF trigger.
- Disable trg_Emp_Update, update Salma, and count her audit rows. Then enable it.
CREATE TABLE HireLog (Id INT IDENTITY, FirstName VARCHAR(20));
GO
CREATE TRIGGER trg_Emp_Insert ON Employees AFTER INSERT
AS INSERT INTO HireLog (FirstName)
SELECT FirstName FROM inserted;
GO
INSERT INTO Employees VALUES (7, 'Layla', 3, 3300);
SELECT FirstName FROM HireLog; -- Layla
CREATE TRIGGER trg_NoDelDept ON Departments
INSTEAD OF DELETE
AS
THROW 50003, 'Departments cannot be deleted.', 1;
DISABLE TRIGGER trg_Emp_Update ON Employees;
UPDATE Employees SET Salary = 3700 WHERE Id = 3;
SELECT COUNT(*) AS AuditRows FROM SalaryAudit
WHERE EmpId = 3; -- 0
ENABLE TRIGGER trg_Emp_Update ON Employees;
Frequently asked questions
Do triggers slow down my database?
They add work to every change on the table, so keep them short and set based. A slow trigger makes every INSERT, UPDATE or DELETE slow.
What is the difference between AFTER and INSTEAD OF?
An AFTER trigger runs once the change has succeeded, which suits auditing. An INSTEAD OF trigger replaces the change, so you can block it or do something else.
Can a trigger handle many rows?
Yes, and it must. The trigger runs once per statement, and inserted and deleted can hold many rows.
What to learn next
Next lesson: Lesson 11: Security: Logins, Users and Roles. Meanwhile, see SQL Server Logins, Users and Permissions and How to Back Up and Restore a SQL Server Database with T-SQL. Previous lesson: Lesson 9: Functions, Temp Tables and Table Variables.
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 (this article)
- 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
- 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 CREATE TRIGGER and related statements.
- Microsoft Learn, SQL Server documentation, for SQL Server Management Studio (SSMS) and the sample concepts.
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…
