📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

What are triggers in SQL Server? Explain AFTER versus INSTEAD OF triggers, the inserted and deleted pseudo-tables, why a trigger must be set-based, the hidden side effects triggers cause, and the alternatives you would consider, such as temporal tables, an outbox table or change data capture.

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.

Mid-Level Theory Intermediate auditing change-data-capture outbox sql-server temporal-tables triggers

🎯 Key points

  • A DML trigger fires once per statement, not once per row; inserted/deleted hold all affected rows
  • AFTER fires after constraints pass, inside the same transaction; INSTEAD OF replaces the action (often on views)
  • Must be set-based: never SELECT @id = id FROM inserted
  • Hidden costs: longer transactions and locks, extra tempdb and log usage, surprise errors, rollback of the caller, nested and recursive triggers
  • Several AFTER triggers on one table run in undefined order apart from sp_settriggerorder first/last
  • EF Core: configure HasTrigger, because by default it reads generated values with OUTPUT (without INTO), which SQL Server rejects on tables with enabled triggers
  • Monitor and test triggers: sys.dm_exec_trigger_stats, integration tests covering multi-row statements
  • Alternatives: temporal tables for history, outbox written by the app, change tracking or CDC for downstream sync

⏱ 30-second answer

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.

🗣 Full answer (senior)

How I would answer this in an interview

"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 vs INSTEAD OF

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)

Trigger alternatives

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

Production example

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.

🔍 What the interviewer is checking

Checks that the candidate understands the trigger execution model and is cautious about the hidden costs.

Green flags

  • States triggers fire per statement and must be set-based
  • Explains inserted/deleted and AFTER vs INSTEAD OF correctly
  • Names hidden costs: longer transactions, rollback of the caller, ORM issues
  • Offers temporal tables, outbox, CDC as alternatives

Red flags

  • Thinks triggers fire once per row
  • Uses triggers to call external services or send email
  • Puts core business logic in triggers by default

📚 Learn in depth

1. Execution model

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.

2. Order, nesting and recursion

  • Several AFTER triggers on one table run in undefined order except first and last (sp_settriggerorder).
  • A trigger that changes another table fires that table's triggers (nested triggers, up to 32 levels).
  • A trigger that changes its own table fires again only if the RECURSIVE_TRIGGERS database option is on.

3. Transactions and errors

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.

4. Detecting which columns changed

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+).

5. EF Core and triggers

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.

6. The alternatives

  • Temporal tables: SYSTEM_VERSIONING = ON keeps every row version in a history table with period columns. Query with FOR SYSTEM_TIME AS OF.
  • Change tracking: lightweight, tells you which keys changed since a version; no old values.
  • CDC: reads the transaction log asynchronously and writes change tables with before and after values; Azure SQL supports it on S3 and above or vCore.
  • Outbox: the app writes the business row and an event row in one transaction; a background process publishes it.

Try it yourself

  1. Write a row-by-row trigger with SELECT @id = Id FROM inserted, run a multi-row UPDATE and see how many audit rows appear.
  2. Rewrite it set-based and compare.
  3. Turn on SET STATISTICS IO ON and observe the trigger's reads appear separately from the main statement.
  4. Convert a table to a temporal table and query FOR SYSTEM_TIME BETWEEN for its history.
  5. Map the table in EF Core without HasTrigger and see the SaveChanges error.

💻 Code

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"));
}

⚠ Common mistakes

  • Mistake: 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.
  • Mistake: Using 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.
  • Mistake: Calling external resources (linked servers, Database Mail, CLR HTTP) from a trigger. Why it is wrong: The caller's transaction waits on them and fails if they fail. Instead: Write an outbox or queue row and process it asynchronously.
  • Mistake: Putting business logic in triggers that the app team doesn't know about. Why it is wrong: Behaviour is invisible, hard to test and surprises ORMs. Instead: Keep triggers rare, tiny and documented; prefer constraints, temporal tables or app code.
  • Mistake: Forgetting 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.
  • Mistake: Issuing 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.

🏛 Senior insight: trade-offs

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

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions temporal tables or audit columns as an alternative Why: Checks the app-side audit approach and when temporal tables fit better.
    How to answer

    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.

  2. When: Candidate mentions CDC as a trigger alternative Why: Checks whether they know the cost and data each feature provides for downstream sync.
    How to answer

    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.

🛠 Real-world problems: how you handle them

Audit trigger blocking checkout during a bulk update
Situation
An [e-commerce] system on Azure SQL had an AFTER UPDATE audit trigger on Orders written years earlier. Operations ran a bulk status update for [50,000] orders after a courier outage.
Signals
Checkout requests timed out for about four minutes; Application Insights showed SQL dependency durations jumping from 20 ms to 30 s; blocking alerts fired with a head blocker running a simple UPDATE.
Investigation
Used sp_WhoIsActive to find the head blocker and its plan; the plan showed the trigger's INSERT into OrderAudit as a heap scan per row via a scalar function. sys.dm_exec_trigger_stats showed the trigger's logical reads far above the UPDATE itself. Reviewed the trigger code and found a row-by-row loop.
Resolution
Immediately: ran the bulk update in batches of 2,000 to shorten lock duration. Fix: replaced the trigger with a system-versioned temporal table, captured the user through an app-side audit column, and added HasTrigger removal in EF Core.
Prevention
Added a review checklist item for triggers, a monitoring query over sys.dm_exec_trigger_stats, and an ADR stating that history uses temporal tables and events use the outbox.

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.

More in SQL Features

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me