Paramclasses Academy - Blog

Tutorials Details

←
Post 28 of 40
→

SQL Server Triggers Explained: AFTER and INSTEAD OF Triggers

SQL Server Triggers Explained: AFTER and INSTEAD OF Triggers

November 18, 2026

???? SQL Server Triggers Explained: AFTER and INSTEAD OF Triggers

???? Introduction

In Microsoft SQL Server, a Trigger is a special type of stored procedure that automatically executes when a specific event occurs in a database.

Triggers help database developers automate tasks such as maintaining audit records, tracking data changes, enforcing business rules, and managing data modifications.

For example, whenever an employee's salary is updated, SQL Server can automatically record the old salary, new salary, employee ID, and update date in an audit table.

In this tutorial by Param Classes, you will learn how SQL Server Triggers work, how to create AFTER and INSTEAD OF triggers, and how to use them with practical SQL examples.

???? What You Will Learn

  1. What is a Trigger in SQL Server?

  2. How SQL Server Triggers work.

  3. Difference between Stored Procedures and Triggers.

  4. Types of SQL Server Triggers.

  5. What is an AFTER Trigger?

  6. What is an INSTEAD OF Trigger?

  7. Understanding INSERTED and DELETED tables.

  8. Creating triggers using practical SQL examples.

  9. Using INSTEAD OF Triggers with Views.

  10. How to enable, disable, and delete triggers.

  11. SQL Server Trigger best practices.


1️⃣ What Is a Trigger in SQL Server?

A Trigger is a database object that automatically executes when a specified event occurs on a table, view, or database.

Unlike a stored procedure, a trigger does not need to be called manually. SQL Server executes it automatically when its associated event occurs.

Example:

Suppose a company maintains an Employees table. Whenever an employee's salary changes, the company wants to store the old and new salary values in an EmployeeAudit table.

Instead of manually inserting audit records every time, we can create a SQL Server Trigger to perform this task automatically.

Basic Trigger Syntax:

CREATE TRIGGER TriggerName
ON TableName
AFTER INSERT, UPDATE, DELETE
AS
BEGIN
    SET NOCOUNT ON;

    -- SQL statements
END;
GO

Important: SQL Server also supports FOR as a synonym for AFTER when defining a DML trigger.


2️⃣ Stored Procedure vs Trigger

Both Stored Procedures and Triggers contain SQL statements, but they work differently.

Feature Stored Procedure Trigger
Execution Called explicitly Executes automatically
Activation EXEC command or application call Associated database event
Parameters Can accept parameters Does not accept regular parameters
Main Purpose Reusable database operations Automatic database actions
Execution Runs when requested Runs when its associated event occurs

Example of Stored Procedure:

EXEC GetEmployeeDetails;

Example of Trigger:

CREATE TRIGGER trg_EmployeeInsert
ON Employees
AFTER INSERT
AS
BEGIN
    PRINT 'New employee inserted';
END;
GO

The trigger executes automatically when an INSERT operation occurs on the Employees table.


3️⃣ Types of SQL Server Triggers

SQL Server supports different types of triggers based on the database event.

A. DML Triggers

DML (Data Manipulation Language) Triggers execute when data is inserted, updated, or deleted.

They are commonly used for:

  • INSERT operations

  • UPDATE operations

  • DELETE operations

DML triggers include:

  • AFTER Triggers

  • INSTEAD OF Triggers

B. DDL Triggers

DDL (Data Definition Language) Triggers execute when database structure-related events occur.

Examples include:

  • CREATE TABLE

  • ALTER TABLE

  • DROP TABLE

  • Other database or server-level DDL events

C. LOGON Triggers

LOGON Triggers execute when a user establishes a connection to SQL Server.

They can be used to manage or restrict login sessions based on specific conditions.

Note: This tutorial mainly focuses on AFTER and INSTEAD OF DML Triggers.


4️⃣ What Is an AFTER Trigger?

An AFTER Trigger executes after the triggering INSERT, UPDATE, or DELETE operation has successfully completed and the applicable constraint checks have passed.

It is useful when you want to perform an automatic action after data modification.

Common Uses:

  • Maintaining audit logs.

  • Tracking employee salary changes.

  • Recording inserted or deleted records.

  • Updating related information.

  • Maintaining business records.

AFTER Trigger Syntax

CREATE TRIGGER TriggerName
ON TableName
AFTER INSERT
AS
BEGIN
    SET NOCOUNT ON;

    -- Trigger logic
END;
GO

You can also specify UPDATE and DELETE events.

CREATE TRIGGER TriggerName
ON TableName
AFTER INSERT, UPDATE, DELETE
AS
BEGIN
    SET NOCOUNT ON;

    -- Trigger logic
END;
GO

5️⃣ Understanding INSERTED and DELETED Tables

SQL Server provides two special logical tables inside DML triggers:

  • INSERTED: Contains the new row values after INSERT or UPDATE operations.

  • DELETED: Contains the old row values before UPDATE or DELETE operations.

These tables are automatically managed by SQL Server and are available within the trigger's execution context.

How INSERTED and DELETED Work

Operation INSERTED Table DELETED Table
INSERT New records No rows
UPDATE Updated records Previous records
DELETE No rows Deleted records

Example: INSERTED Table

SELECT *
FROM inserted;

This retrieves the newly inserted or updated rows inside a trigger.

Example: DELETED Table

SELECT *
FROM deleted;

This retrieves the previous or deleted rows inside a trigger.

Important: An UPDATE operation makes both tables useful: DELETED contains the old values, while INSERTED contains the new values.


6️⃣ Practical SQL Server Trigger Example

Let's create a practical employee database example.

We will create two tables:

  1. Employees – Stores employee information.

  2. EmployeeAudit – Stores employee data modification history.

Step 1: Create the Employees Table

CREATE TABLE Employees
(
    EmployeeID INT IDENTITY(1,1) PRIMARY KEY,
    EmployeeName VARCHAR(100) NOT NULL,
    Department VARCHAR(50),
    Salary DECIMAL(10,2) NOT NULL
);
GO

Step 2: Create the EmployeeAudit Table

CREATE TABLE EmployeeAudit
(
    AuditID INT IDENTITY(1,1) PRIMARY KEY,
    EmployeeID INT,
    ActionType VARCHAR(20),
    OldSalary DECIMAL(10,2),
    NewSalary DECIMAL(10,2),
    ActionDate DATETIME2 DEFAULT SYSDATETIME()
);
GO

This table will store information about employee INSERT, UPDATE, and DELETE operations.

Step 3: Create an AFTER INSERT Trigger

CREATE TRIGGER trg_EmployeeInsert
ON Employees
AFTER INSERT
AS
BEGIN
    SET NOCOUNT ON;

    INSERT INTO EmployeeAudit
    (
        EmployeeID,
        ActionType,
        OldSalary,
        NewSalary
    )
    SELECT
        EmployeeID,
        'INSERT',
        NULL,
        Salary
    FROM inserted;
END;
GO

Explanation:

  • The trigger executes after a successful INSERT operation.

  • The inserted table provides the newly inserted employee records.

  • Employee details are automatically recorded in EmployeeAudit.

  • Multiple inserted rows are handled by a single set-based INSERT statement.

Step 4: Insert Employee Records

INSERT INTO Employees
(
    EmployeeName,
    Department,
    Salary
)
VALUES
('Rahul Sharma', 'IT', 35000),
('Priya Verma', 'HR', 30000),
('Amit Kumar', 'Sales', 28000);
GO

Step 5: Check Employee Records

SELECT *
FROM Employees;

Step 6: Check Automatically Created Audit Records

SELECT *
FROM EmployeeAudit;

Expected Result:

The EmployeeAudit table will contain three records with ActionType = 'INSERT'.

No separate INSERT statement was required for the audit table because the trigger handled it automatically.


7️⃣ Create an AFTER UPDATE Trigger

Now suppose an employee's salary changes. We want to store both the old and new salary values.

CREATE TRIGGER trg_EmployeeUpdate
ON Employees
AFTER UPDATE
AS
BEGIN
    SET NOCOUNT ON;

    INSERT INTO EmployeeAudit
    (
        EmployeeID,
        ActionType,
        OldSalary,
        NewSalary
    )
    SELECT
        d.EmployeeID,
        'UPDATE',
        d.Salary,
        i.Salary
    FROM deleted AS d
    INNER JOIN inserted AS i
        ON d.EmployeeID = i.EmployeeID;
END;
GO

Test the UPDATE Trigger

UPDATE Employees
SET Salary = 40000
WHERE EmployeeID = 1;
GO

Now check the audit table:

SELECT *
FROM EmployeeAudit
ORDER BY AuditID DESC;

Explanation:

  • deleted contains the employee's previous salary.

  • inserted contains the employee's updated salary.

  • Both tables are joined using EmployeeID.

  • The trigger automatically stores the old and new salary values.


8️⃣ Create an AFTER DELETE Trigger

We can also record employee details when an employee is deleted.

CREATE TRIGGER trg_EmployeeDelete
ON Employees
AFTER DELETE
AS
BEGIN
    SET NOCOUNT ON;

    INSERT INTO EmployeeAudit
    (
        EmployeeID,
        ActionType,
        OldSalary,
        NewSalary
    )
    SELECT
        EmployeeID,
        'DELETE',
        Salary,
        NULL
    FROM deleted;
END;
GO

Test the DELETE Trigger

DELETE FROM Employees
WHERE EmployeeID = 2;
GO

Check the audit records:

SELECT *
FROM EmployeeAudit
ORDER BY AuditID DESC;

The deleted employee's ID and previous salary will be stored in EmployeeAudit.

Practical Learning: With these three triggers, we have created a simple automatic audit system for employee records.


9️⃣ What Is an INSTEAD OF Trigger?

An INSTEAD OF Trigger executes in place of the original INSERT, UPDATE, or DELETE operation.

In other words, SQL Server runs the trigger's logic instead of directly performing the requested modification on the target table or view.

It is particularly useful when working with views that combine data from multiple tables or when custom logic is required before modifying underlying data.

INSTEAD OF Trigger Syntax

CREATE TRIGGER TriggerName
ON TableName
INSTEAD OF INSERT
AS
BEGIN
    SET NOCOUNT ON;

    -- Custom SQL logic
END;
GO

Difference Between AFTER and INSTEAD OF Triggers

Feature AFTER Trigger INSTEAD OF Trigger
Execution After the triggering operation In place of the triggering operation
Main Purpose Perform actions after modification Replace or customize modification logic
Views Cannot be defined on views Can be defined on views
Common Use Audit logging Custom view modifications
Data Handling Uses inserted and deleted tables Uses inserted and deleted tables

???? Practical INSTEAD OF Trigger Example Using a View

Let's create a view for employee information and use an INSTEAD OF INSERT trigger to control how records are inserted into the underlying Employees table.

Step 1: Create an Employee View

CREATE VIEW vw_EmployeeDetails
AS
SELECT
    EmployeeID,
    EmployeeName,
    Department,
    Salary
FROM Employees;
GO

Step 2: Create an INSTEAD OF INSERT Trigger

CREATE TRIGGER trg_InsteadOfEmployeeInsert
ON vw_EmployeeDetails
INSTEAD OF INSERT
AS
BEGIN
    SET NOCOUNT ON;

    INSERT INTO Employees
    (
        EmployeeName,
        Department,
        Salary
    )
    SELECT
        EmployeeName,
        Department,
        Salary
    FROM inserted;
END;
GO

Explanation:

  • The trigger is created on the view.

  • When an INSERT statement is issued against the view, the trigger executes instead of the view's normal INSERT action.

  • The trigger reads the supplied values from inserted.

  • It inserts the records into the actual Employees table.

  • The EmployeeID is generated automatically by the identity property.

Step 3: Insert Data Through the View

INSERT INTO vw_EmployeeDetails
(
    EmployeeName,
    Department,
    Salary
)
VALUES
('Neha Singh', 'Marketing', 32000);
GO

Step 4: Check the Employees Table

SELECT *
FROM Employees;

The new employee record will be stored in the Employees table through the INSTEAD OF trigger.

Important: The Employees table's AFTER INSERT trigger will also execute when the INSTEAD OF trigger inserts a record into the base table. Therefore, the audit record will be created automatically.


1️⃣1️⃣ How to Disable and Enable a Trigger

Sometimes, database administrators may need to temporarily stop a trigger from executing.

Disable a Trigger

DISABLE TRIGGER trg_EmployeeInsert
ON Employees;
GO

Enable a Trigger

ENABLE TRIGGER trg_EmployeeInsert
ON Employees;
GO

Remember: Disabling a trigger does not delete it. The trigger remains in the database but does not execute until it is enabled again.


1️⃣2️⃣ How to Delete a Trigger

If a trigger is no longer required, you can remove it using the DROP TRIGGER statement.

DROP TRIGGER IF EXISTS trg_EmployeeInsert;
GO

To delete another trigger:

DROP TRIGGER IF EXISTS trg_EmployeeUpdate;
GO

Note: Dropping a trigger removes the trigger object, but it does not delete the table on which the trigger was created.


1️⃣3️⃣ SQL Server Trigger Best Practices

Follow these practices when creating triggers in real-world applications.

1. Keep Trigger Logic Simple

Avoid writing unnecessary or complicated SQL statements inside triggers.

2. Handle Multiple Rows

A single INSERT, UPDATE, or DELETE statement can affect multiple records. Always use set-based operations with inserted and deleted instead of assuming only one row will be affected.

3. Avoid Unnecessary Triggers

Too many triggers can make database operations difficult to understand, maintain, and troubleshoot.

4. Use SET NOCOUNT ON

Use SET NOCOUNT ON to suppress unnecessary row-count messages generated by statements inside the trigger.

5. Test Trigger Behavior

Always test INSERT, UPDATE, and DELETE operations with both single-row and multiple-row examples.

6. Consider Performance

Triggers execute as part of the triggering database operation. Complex trigger logic can increase query execution time.

7. Avoid Hidden Side Effects

Document triggers clearly so developers and database administrators understand which automatic operations occur when data changes.


1️⃣4️⃣ Frequently Asked Questions (FAQs)

Q1. What is a Trigger in SQL Server?

A Trigger is a special database object that automatically executes when a specified database event occurs.

Q2. What are the main types of SQL Server DML Triggers?

The two main DML trigger types covered here are AFTER and INSTEAD OF triggers.

Q3. What is an AFTER Trigger?

An AFTER Trigger executes after the triggering data modification succeeds and the applicable constraints are satisfied.

Q4. What is an INSTEAD OF Trigger?

An INSTEAD OF Trigger executes in place of the original INSERT, UPDATE, or DELETE operation.

Q5. What is the difference between INSERTED and DELETED tables?

The INSERTED table contains new or updated row values, whereas the DELETED table contains old or deleted row values.

Q6. Can we create a Trigger on a View in SQL Server?

Yes. SQL Server supports INSTEAD OF triggers on views.

Q7. Can a Trigger handle multiple records?

Yes. A properly designed trigger can handle multiple affected records using set-based SQL statements.

Q8. Can we disable a Trigger without deleting it?

Yes. You can use the DISABLE TRIGGER statement and enable it again using ENABLE TRIGGER.

Q9. What is the difference between a Stored Procedure and a Trigger?

A stored procedure is generally executed explicitly, whereas a trigger executes automatically when its associated event occurs.

Q10. Are Triggers useful in real-world database applications?

Yes. Triggers are useful for audit logging, tracking data changes, and implementing specific database business rules.


???? Conclusion

SQL Server Triggers are an important feature for automating database operations and maintaining data consistency.

In this tutorial, we learned about AFTER Triggers, INSTEAD OF Triggers, INSERTED and DELETED tables, and how to create practical triggers for INSERT, UPDATE, and DELETE operations.

We also explored how triggers can be used with views, how to enable and disable them, and how to maintain audit records automatically.

Understanding SQL Server Triggers will help you build more reliable and manageable database applications.

At Param Classes, our goal is to provide practical, step-by-step programming and database tutorials that help students develop real-world technical skills.

Keep learning, keep practicing, and build your SQL Server skills with Param Classes!

←
Post 28 of 40
→