SQL Server DML triggers: AFTER and INSTEAD OF, inserted and deleted, writing them set-based, their hidden costs, and alternatives such as temporal tables, the outbox pattern, change tracking and CDC.
A DML trigger is code that runs automatically on INSERT, UPDATE or DELETE, once per statement, inside the same transaction. The inserted and deleted pseudo-tables hold every affected row, so a trigger must be set-based; SELECT @id = Id FROM inserted silently handles only one row. AFTER triggers run once the change and constraints have succeeded; INSTEAD OF triggers replace the action, typically to make a view updatable.
Triggers are invisible to callers: they lengthen transactions, can fail or roll back someone else's write, and surprise ORMs (EF Core needs HasTrigger). For auditing I'd prefer temporal tables, for events an outbox written by the app, and for downstream sync change tracking or CDC.
"A trigger is a piece of T-SQL that SQL Server runs automatically when a table changes. The key mechanics: it fires once per statement, not once per row, and it runs inside the caller's transaction. Inside it I get two pseudo-tables, inserted and deleted, holding the new and old versions of every affected row; an UPDATE fills both. An AFTER trigger runs once the statement and its constraints have succeeded, so it can audit or enforce a cross-table rule and roll back if needed. An INSTEAD OF trigger runs instead of the statement, which is mostly used to make a complex view updatable.
Because it fires per statement, the trigger must be set-based. The classic bug is SELECT @OrderId = OrderId FROM inserted, which works in every test that inserts one row and silently ignores 999 rows when someone does a bulk update. I always write the trigger as an INSERT ... SELECT or UPDATE ... JOIN against inserted.
My bigger concern is that triggers are hidden. A developer runs a simple UPDATE and it takes three seconds because a trigger writes to an audit table with no index, or it fails because the trigger called a linked server. They extend the transaction, so locks are held longer, and an error inside them rolls back the caller's work. EF Core also has to be told: on SQL Server you configure HasTrigger, otherwise SaveChanges fails because EF uses OUTPUT without INTO.
So I reach for alternatives first. For history and audit, temporal tables give me system-versioned history without code. For publishing events, I write an outbox row in the same transaction from the application. For feeding a warehouse or search index, change tracking or CDC. I still use triggers occasionally for a rule the database must enforce no matter who writes, but kept tiny and documented."
| AFTER | INSTEAD OF | |
|---|---|---|
| When it runs | After the statement and constraint checks | In place of the statement |
| On | Tables only | Tables and views |
| Typical use | Audit, cross-table rules, denormalised counters | Updatable views, soft delete on DELETE |
| Rows available | inserted, deleted |
inserted, deleted (the proposed change) |
| Need | Better option | Why |
|---|---|---|
| Row history / audit | System-versioned temporal tables | Built in, queryable with FOR SYSTEM_TIME, no code |
| Who changed it | App-level audit columns or an interceptor, or temporal table + user column | Triggers only see the SQL login unless you pass SESSION_CONTEXT |
| Publish domain events | Transactional outbox from the app | Explicit, testable, retries outside the transaction |
| Sync to search or a warehouse | Change tracking or CDC | Asynchronous, doesn't slow the writer |
| Enforce a rule all writers must obey | Constraint first; trigger only if a constraint can't express it | Constraints are cheaper and visible |
An audit trigger on Orders inserted into an unindexed OrderAudit heap and called a scalar function per row. A bulk status update of 50,000 orders took 4 minutes and blocked checkout. Replacing it with a temporal table removed the trigger, and the same update took 3 seconds.
Checks that the candidate understands the trigger execution model and is cautious about the hidden costs.
Green flags
Red flags
UPDATE dbo.Orders SET Status = 'Shipped' WHERE BatchId = 7 -- 5,000 rows
|
+-- rows modified, constraints checked
|
+-- AFTER trigger fires ONCE
| inserted: 5,000 new rows
| deleted: 5,000 old rows
|
+-- transaction commits only if the trigger succeeds
The trigger fires even if zero rows are affected, so check IF NOT EXISTS (SELECT 1 FROM inserted) RETURN; at the top. inserted and deleted are built from the row version store, so large modifications cost tempdb space.
sp_settriggerorder).RECURSIVE_TRIGGERS database option is on.A trigger runs inside the statement's transaction. With XACT_ABORT on by default inside triggers, any run-time error dooms the whole transaction. ROLLBACK inside a trigger rolls back the caller's transaction too and raises error 3609 in the batch. Use THROW with a clear message instead of a silent rollback.
UPDATE(column) tells you a column was in the SET list, not that its value changed. Compare inserted with deleted on the key to find real changes, handling NULLs with IS DISTINCT FROM (SQL Server 2022+).
EF Core on SQL Server uses OUTPUT to read generated values. OUTPUT without INTO is not allowed on tables with enabled triggers, so you configure tb.HasTrigger("trg_Orders_Audit") and EF Core switches to a slower but compatible approach.
SYSTEM_VERSIONING = ON keeps every row version in a history table with period columns. Query with FOR SYSTEM_TIME AS OF.SELECT @id = Id FROM inserted, run a multi-row UPDATE and see how many audit rows appear.SET STATISTICS IO ON and observe the trigger's reads appear separately from the main statement.FOR SYSTEM_TIME BETWEEN for its history.HasTrigger and see the SaveChanges error.A set-based audit trigger, and the temporal table I'd usually use instead.
-- Set-based AFTER UPDATE trigger: one INSERT for all affected rows
CREATE OR ALTER TRIGGER dbo.trg_Orders_StatusAudit
ON dbo.Orders
AFTER UPDATE
AS
BEGIN
SET NOCOUNT ON;
IF NOT EXISTS (SELECT 1 FROM inserted) RETURN; -- fires even for 0 rows
INSERT dbo.OrderStatusAudit (OrderId, OldStatus, NewStatus, ChangedAt, ChangedBy)
SELECT i.OrderId, d.Status, i.Status, SYSUTCDATETIME(),
CAST(SESSION_CONTEXT(N'UserId') AS nvarchar(100)) -- set by the app per request
FROM inserted i
JOIN deleted d ON d.OrderId = i.OrderId
WHERE i.Status IS DISTINCT FROM d.Status; -- only real changes (SQL Server 2022+)
END;
GO
-- Usually better: a system-versioned temporal table, no trigger code
ALTER TABLE dbo.Orders ADD
ValidFrom datetime2 GENERATED ALWAYS AS ROW START HIDDEN NOT NULL
CONSTRAINT DF_Orders_ValidFrom DEFAULT SYSUTCDATETIME(),
ValidTo datetime2 GENERATED ALWAYS AS ROW END HIDDEN NOT NULL
CONSTRAINT DF_Orders_ValidTo DEFAULT CONVERT(datetime2, '9999-12-31 23:59:59.9999999'),
PERIOD FOR SYSTEM_TIME (ValidFrom, ValidTo);
ALTER TABLE dbo.Orders SET (SYSTEM_VERSIONING = ON (HISTORY_TABLE = dbo.OrdersHistory));
GO
SELECT OrderId, Status, ValidFrom, ValidTo
FROM dbo.Orders FOR SYSTEM_TIME ALL
WHERE OrderId = 1001
ORDER BY ValidFrom;
namespace Shop.Infrastructure;
public sealed class OrderConfiguration : IEntityTypeConfiguration<Order>
{
public void Configure(EntityTypeBuilder<Order> builder) =>
// Tell EF Core about the trigger so SaveChanges doesn't use OUTPUT without INTO
builder.ToTable("Orders", tb => tb.HasTrigger("trg_Orders_StatusAudit"));
}
SELECT @Id = Id FROM inserted. Why it is wrong: Triggers fire once per statement; multi-row changes are silently handled for one row only. Instead: Join inserted and deleted in set-based statements.UPDATE(Status) to mean "the status changed". Why it is wrong: It is true whenever the column is in the SET list, even if the value is the same. Instead: Compare inserted and deleted values.HasTrigger in EF Core. Why it is wrong: SaveChanges fails because EF Core uses OUTPUT without INTO. Instead: Configure HasTrigger for every table with triggers.ROLLBACK in a trigger to reject a change. Why it is wrong: It ends the caller's whole transaction and raises a confusing error 3609. Instead: THROW a meaningful error and let the caller decide.Triggers are the right tool in a narrow band: a rule that every writer must obey, that a constraint can't express, and that's cheap to evaluate. Outside that band they turn a simple write into a hidden transaction with side effects. When I inherit a system with lots of triggers, the first job is to list them (sys.triggers, including is_disabled and sp_settriggerorder settings) and measure their cost, because they're often the reason for mysterious blocking.
If a trigger stays, I treat it like production code: an integration test that runs single-row and multi-row statements (Testcontainers or tSQLt), a dashboard on sys.dm_exec_trigger_stats (execution count, worker time, logical reads) so its cost is visible as data grows, and a note in the table's documentation so the app team knows it exists.
| Option | Fits when | Cost | Not when |
|---|---|---|---|
| AFTER trigger | Cross-table rule all writers must obey | Hidden work in every write transaction, extra tempdb and log | Calling external systems |
| Temporal table | Full row history, point-in-time queries | History storage, needs retention policy | You need who-and-why without extra columns |
| Outbox | Reliable event publishing | App code and a relay | Non-app writers must also publish |
| CDC / change tracking | Downstream sync | Log reader overhead, Azure tier limits | Synchronous consistency needed |
Entities implement IAuditable (CreatedAt, CreatedBy, ModifiedAt, ModifiedBy). A SaveChangesInterceptor walks the change tracker: for Added entries it sets the created fields, for Modified entries the modified fields, and it marks the created fields as not modified so updates cannot change them. Time comes from TimeProvider so tests can freeze it; the user comes from a scoped current-user service.
It misses anything that skips the change tracker: ExecuteUpdate, raw SQL and other tools. And audit columns only tell you who last touched a row, not what changed. When you need full history, SQL Server temporal tables keep every version, at the cost of storage and without the app user unless you add it.
Change tracking records which primary keys changed since a version number, synchronously and cheaply, but keeps no old values or history of intermediate changes; you re-read the current row. CDC reads the transaction log asynchronously and writes change tables with before and after values for every change, so it suits feeding a warehouse or an event stream. Change tracking fits "sync what changed" (mobile sync, cache refresh); CDC fits auditing column values or streaming to Kafka or Fabric. CDC costs more storage and on Azure SQL needs S3+ or vCore.
How to tell it (STAR)
**S:** At [company], a bulk order update blocked checkout for several minutes. **T:** I had to find the cause and stop it happening again. **A:** I used sp_WhoIsActive and the plan to show the real work was in an old audit trigger that looped row by row into an unindexed table. I batched the immediate update, then replaced the trigger with a temporal table and moved the 'who' into an app-set column. **R:** The same 50,000-row update dropped from about [4 minutes] to [3 seconds], and checkout stopped timing out during bulk operations.
Last updated 23 Nov 2026.