SQL Server Triggers

Do you know the power and the danger of SQL Server triggers? A trigger is a special stored procedure that runs automatically when a data change or schema event happens. Used well, it gives you reliable audit trails and enforces rules that constraints cannot express. Used carelessly, it creates mystery slowdowns, blocking, and data bugs.

This guide shows you how triggers work, how to write safe multi-row versions, how to secure them, and how to test and monitor them, including in Azure SQL.

How SQL Server Triggers Work

A trigger is code attached to a table, view, database, or server that fires when a specific event occurs. SQL Server has three families:

  • DML triggers: Fire on INSERT, UPDATE, or DELETE.
  • DDL triggers: Fire on schema events such as CREATE TABLE or DROP TABLE.
  • Logon triggers: Fire when a session connects to the server.

DML triggers come in two types. An AFTER trigger runs once the statement and its constraint checks succeed. It is for reactions such as auditing. An INSTEAD OF trigger replaces the original statement, and you can define only one per action on a table. Its main legitimate use is making complex views updatable.

SQL Server has no BEFORE trigger. Two behaviors cause most bugs:

  • Per statement, not per row: A trigger fires once for a statement, no matter how many rows it changes. It can even fire when zero rows change.
  • Same transaction: The trigger runs inside the transaction of the statement that fired it. If the trigger fails, the whole change rolls back.

Inside a DML trigger, two virtual tables hold the affected rows:

Statementinserted holdsdeleted holds
INSERTNew rowsNothing
UPDATERows after the changeRows before the change
DELETENothingRemoved rows

If tables, keys, and constraints are new to you, review SQL constraints and primary key vs. foreign key first. Constraints should come first, because they are faster and more predictable than triggers.

Pro Tip: In my experience, I ask one question before writing any trigger: can a constraint, a stored procedure, or a temporal table do this instead? About half the time, the answer is yes.

Set Up a Realistic Audit Scenario

Let’s build an order-management example. The schema is a named container for database objects, and here we use dbo.

CREATE TABLE dbo.Orders
(
OrderId int IDENTITY(1,1) CONSTRAINT PK_Orders PRIMARY KEY,
CustomerId int NOT NULL,
Status varchar(20) NOT NULL,
TotalUsd decimal(12,2) NOT NULL
);

CREATE TABLE dbo.OrderAudit
(
AuditId bigint IDENTITY(1,1) CONSTRAINT PK_OrderAudit PRIMARY KEY,
OrderId int NOT NULL,
OldStatus varchar(20) NULL,
NewStatus varchar(20) NULL,
ChangedBy sysname NOT NULL,
ChangedAtUtc datetime2(0) NOT NULL
);


After running the above quries, the tables have been created successfully as shown in the screenshot below.
create sql server triggers

The first table stores orders. The second stores a history of status changes, including who changed them and when. Both use primary keys that auto-number through an identity column. See create table with an identity column for details, and database design best practices if you want to model the audit table well.

Pro Tip: I always store audit timestamps in UTC using SYSUTCDATETIME(). Mixed time zones make audit trails nearly impossible to read during an incident.

Create a Safe AFTER Trigger

This trigger logs every status change. It is written for multiple rows from the start.

CREATE OR ALTER TRIGGER dbo.trg_Orders_AuditStatus
ON dbo.Orders
AFTER UPDATE
AS
BEGIN
IF @@ROWCOUNT = 0 RETURN;
SET NOCOUNT ON;

IF NOT UPDATE(Status) RETURN;

INSERT INTO dbo.OrderAudit (OrderId, OldStatus, NewStatus, ChangedBy, ChangedAtUtc)
SELECT i.OrderId, d.Status, i.Status, ORIGINAL_LOGIN(), SYSUTCDATETIME()
FROM inserted AS i
JOIN deleted AS d ON d.OrderId = i.OrderId
WHERE ISNULL(i.Status, '') <> ISNULL(d.Status, '');
END;

After running the query above, the trigger is created successfully, as shown in the screenshot below.

SQL Server Triggers

Here is what each part does:

  • CREATE OR ALTER creates the trigger or updates it if it exists.
  • AFTER UPDATE fires it after an UPDATE succeeds.
  • IF @@ROWCOUNT = 0 RETURN; exits early when the statement changed no rows, which Microsoft recommends to shorten trigger duration. It must come before SET NOCOUNT ON, because SET statements reset the count.
  • IF NOT UPDATE(Status) RETURN; skips the work when the Status column was not part of the update.
  • The INSERT ... SELECT joins inserted and deleted on the primary key and writes one audit row per changed order, so it works for one row or one million.
  • ORIGINAL_LOGIN() records the person who connected, even when code runs under another context.

Test it with a multi-row update:

UPDATE dbo.Orders SET Status = 'Shipped' WHERE Status = 'Packed';
SELECT TOP (10) * FROM dbo.OrderAudit ORDER BY AuditId DESC;

The UPDATE changes every packed order, and the SELECT shows the audit rows. Run this only in a test database, since the UPDATE changes data. For more on safe updates, see how to find who updated a table, which covers other ways to trace changes.

Pro Tip: I test every trigger with three cases: one row, many rows, and zero rows. The zero-row case catches bugs that only appear during maintenance jobs.

The Multi-Row Mistake to Avoid

This is the most common trigger bug I see:

-- BROKEN: handles only one arbitrary row
DECLARE @OrderId int, @NewStatus varchar(20);
SELECT @OrderId = OrderId, @NewStatus = Status FROM inserted;

When a statement changes 500 rows, this code picks one and silently ignores the rest. There is no error, only missing audit data. The fix is never a cursor. Use set-based logic against inserted and deleted, as in the working example above. A cursor is a row-by-row loop, and it is slow inside a trigger because the statement’s locks stay held for the whole loop.

If you must understand loops for other code, see the WHILE loop in a stored procedure, but keep them out of triggers.

Pro Tip: I once found a trigger that audited only the first row of each bulk update. The audit table looked healthy for two years, and nobody noticed until a compliance review.

INSTEAD OF Triggers and Soft Deletes

An INSTEAD OF trigger replaces the statement, so you control what happens. A common use is a soft delete, which marks a row as deleted instead of removing it. This version needs a flag column:

ALTER TABLE dbo.Orders ADD IsDeleted bit NOT NULL CONSTRAINT DF_Orders_IsDeleted DEFAULT (0);
GO

CREATE OR ALTER TRIGGER dbo.trg_Orders_SoftDelete
ON dbo.Orders
INSTEAD OF DELETE
AS
BEGIN
SET NOCOUNT ON;
UPDATE o
SET IsDeleted = 1
FROM dbo.Orders AS o
JOIN deleted AS d ON d.OrderId = o.OrderId;
END;

The ALTER TABLE statement changes the table structure, so run it first in a test environment. After that, a DELETE on dbo.Orders no longer removes rows. It flips IsDeleted to 1, which keeps history for audits and undo. Your queries must then filter on IsDeleted = 0, which is the trade-off.

After running the query above, I got the expected output shown in the screenshot below.

how to create triggers in sql server

Compare this with normal deletes in how to delete data from a table so you understand what you are overriding. Because INSTEAD OF triggers surprise developers, document them clearly.

Pro Tip: I add a comment and a README note for every INSTEAD OF trigger. A DELETE that does not delete is confusing for the next developer.

DDL Triggers for Schema Changes

A DDL trigger can record or block structural changes, which helps in shared environments:

CREATE TABLE dbo.SchemaChangeLog
(
LogId int IDENTITY(1,1) PRIMARY KEY,
EventType nvarchar(100),
ObjectName nvarchar(256),
LoginName nvarchar(256),
EventXml xml,
LoggedAtUtc datetime2(0) DEFAULT SYSUTCDATETIME()
);
GO

CREATE OR ALTER TRIGGER trg_LogSchemaChanges
ON DATABASE
FOR DROP_TABLE, ALTER_TABLE
AS
BEGIN
SET NOCOUNT ON;
DECLARE @e xml = EVENTDATA();
INSERT INTO dbo.SchemaChangeLog (EventType, ObjectName, LoginName, EventXml)
VALUES (
@e.value('(/EVENT_INSTANCE/EventType)[1]', 'nvarchar(100)'),
@e.value('(/EVENT_INSTANCE/ObjectName)[1]', 'nvarchar(256)'),
@e.value('(/EVENT_INSTANCE/LoginName)[1]', 'nvarchar(256)'),
@e
);
END;

ON DATABASE scopes the trigger to one database. EVENTDATA() returns an XML description of the event, and the code extracts the event type, object name, and login. This gives you a record of who dropped or altered a table.

Be careful with scope. Database-level DDL triggers work in Azure SQL Database. Server-level triggers, such as ON ALL SERVER and logon triggers, are not available there, while Azure SQL Managed Instance and SQL Server on a VM support them. Check feature support for your platform before you design around them. Learn about the risk behind this trigger in SQL DROP TABLE.

Pro Tip: I pair DDL triggers with a restricted admin group. Logging is useful, but fewer people with schema rights is a stronger control.

Secure Your Triggers

Triggers run with the permissions of the user whose statement fired them, unless you set EXECUTE AS. That has security consequences.

  • Protect the audit table: The application user should be able to insert through the trigger but not update or delete audit rows. Deny those rights directly.
  • Avoid sysadmin: Never run the application as sa or sysadmin to “make the trigger work.” Grant only what the trigger writes.
  • Use Entra ID: In Azure SQL, create contained users from Microsoft Entra ID instead of SQL passwords.
  • Control who can alter triggers: The ALTER permission on a table lets someone change or disable its triggers. Review it using object-level permissions and SQL Server permissions.
CREATE USER [orders-app] FROM EXTERNAL PROVIDER;
GRANT SELECT, INSERT, UPDATE ON dbo.Orders TO [orders-app];
DENY UPDATE, DELETE ON dbo.OrderAudit TO [orders-app];

The first statement creates a contained database user mapped to an Entra identity or managed identity. The second grants normal table access. The DENY statement stops the app from altering audit history, and DENY overrides any grant. If the trigger writes audit rows under the caller’s permissions, test that this setup still works, because a missing permission will make the original UPDATE fail. In some designs, you sign the trigger with EXECUTE AS or module signing instead.

Always test with a non-admin account, and verify encryption on the connection:

SELECT encrypt_option FROM sys.dm_exec_connections WHERE session_id = @@SPID;

This should return TRUE, confirming TLS. Connect to Azure SQL with SSMS over a private endpoint or a restricted firewall rule, never a rule that opens every address.

Pro Tip: I once saw an audit trigger fail only for a service account, because it lacked INSERT rights on the audit table. Testing as a normal user would have caught it before release.

Manage, Monitor, and Troubleshoot

List triggers in a database to find hidden ones:

SELECT t.name AS trigger_name,
OBJECT_NAME(t.parent_id) AS table_name,
t.is_disabled,
t.is_instead_of_trigger
FROM sys.triggers AS t
WHERE t.parent_class = 1;

This reads the sys.triggers catalog view and shows each table trigger, whether it is disabled, and whether it is INSTEAD OF. Run it on any database you inherit.

Check how much work triggers perform:

SELECT OBJECT_NAME(object_id) AS trigger_name,
execution_count,
total_elapsed_time / 1000 AS total_ms
FROM sys.dm_exec_trigger_stats
ORDER BY total_elapsed_time DESC;

This dynamic management view (DMV) reports execution counts and elapsed time for triggers. Look at it when bulk loads slow down. In Azure SQL, Query Store and Azure Monitor alerts give you history and early warning.

To pause a trigger during a controlled bulk load, disable it, then re-enable it:

DISABLE TRIGGER dbo.trg_Orders_AuditStatus ON dbo.Orders;
-- run the bulk load here
ENABLE TRIGGER dbo.trg_Orders_AuditStatus ON dbo.Orders;

Disabling a trigger skips its logic, so audit rows will be missing. Document the window and fill the gap afterward. Only do this with approval.

Common problems and fixes:

  • Slow bulk operations: The trigger scans tables or loops row by row. Rewrite it set-based and index the join columns. See how to create an index and query optimization tips.
  • Blocking or deadlocks: Long triggers hold locks longer. Keep them short. Read about deadlock victims.
  • Unexpected recursion: An AFTER trigger does not call itself unless the RECURSIVE_TRIGGERS database option is on. Nested triggers can reach 32 levels. Avoid order-dependent chains.
  • Lost updates in audit data: Check for single-row assumptions.

For alternatives, consider temporal tables, which SQL Server 2016 and later can use to keep row history with less code, and ordinary stored procedures when business logic belongs in a single controlled path. The article on functions vs. stored procedures helps you choose.

Pro Tip: I add trigger execution stats to my regular performance review. A trigger that quietly doubles write time is easy to miss until users complain.

Frequently Asked Questions

What is a trigger in SQL Server?

A trigger is a special stored procedure that runs automatically when an INSERT, UPDATE, DELETE, schema change, or logon event occurs. It runs in the same transaction as the statement that fired it.

What is the difference between AFTER and INSTEAD OF triggers?

An AFTER trigger runs after the statement succeeds and is used for reactions like auditing. An INSTEAD OF trigger replaces the statement entirely, and only one is allowed per action on a table.

Do triggers slow down SQL Server?

They can, because they run inside the original transaction and hold locks until they finish. Short, set-based, indexed triggers add little overhead. Row-by-row loops and remote calls cause serious slowdowns.

How do I see all triggers in a database?

Query sys.triggers, or expand the Triggers folder under a table in SSMS. Check is_disabled to find triggers that are turned off.

Do triggers work in Azure SQL Database?

DML triggers and database-level DDL triggers work. Server-level and logon triggers are not available in Azure SQL Database, but they are available in Managed Instance and SQL Server on a VM.

You May Also Like

You learned how DML and DDL triggers work, how to write multi-row-safe audit logic, and how to secure, monitor, and troubleshoot them. Keep triggers short and set-based, protect audit tables from the application user, and test a restore before you ship data-changing code. I hope you found this article helpful.