Master SQL Server From Scratch

Clear, interactive, and structured SQL Server lessons designed for beginners and developers.

COURSE SYLLABUS
1. Introduction to SQL Server
Introduction to SQL Server SQL Server Installation SQL Server Fundamentals
2. Data Types
Data Types Numeric Data Types Character & String Data Types Date & Time Data Types Other SQL Server Data Types
3. Database & Tables
Database & Tables Introduction Creating a Database Creating Tables Table Structure Altering Tables Dropping Tables
4. Constraints
Constraints Introduction PRIMARY KEY FOREIGN KEY UNIQUE Constraint NOT NULL & DEFAULT CHECK Constraint
5. SQL Basics
SQL Basics Introduction SQL Commands SQL Command Categories SELECT Statement INSERT, UPDATE & DELETE
6. CRUD Operations
CRUD Operations Introduction INSERT Operation SELECT Operation UPDATE Operation DELETE Operation
7. SQL Queries
Queries Introduction WHERE Clause ORDER BY Clause DISTINCT LIKE Operator IN, BETWEEN & IS NULL
8. Joins
Joins Introduction INNER JOIN LEFT JOIN RIGHT JOIN FULL OUTER JOIN CROSS JOIN
9. SQL Functions
SQL Functions Introduction String Functions Numeric Functions Date & Time Functions Conversion Functions NULL Functions
10. Grouping & Aggregate Functions
GROUP BY Aggregate Functions COUNT() SUM() AVG() MIN() & MAX()
11. Subqueries
Subqueries Introduction Single-Row Subquery Multiple-Row Subquery Correlated Subquery Subquery with DML
12. Views
SQL Views Introduction Creating a View Updating a View Altering a View Dropping a View
13. Stored Procedures
Stored Procedures Introduction Creating a Stored Procedure Input Parameters Output Parameters Executing & Modifying Stored Procedures
14. Triggers
Triggers Introduction AFTER INSERT Trigger AFTER UPDATE Trigger AFTER DELETE Trigger INSTEAD OF Trigger
15. Transactions
Transactions Introduction COMMIT ROLLBACK SAVEPOINT Transaction with TRY...CATCH
16. Indexes
Indexes Introduction Clustered Index Non-Clustered Index Creating & Dropping Indexes Index Performance
17. Common Table Expressions
CTE Introduction Simple CTE CTE with JOIN CTE with Aggregate Functions Recursive CTE
18. Window Functions
Window Functions Introduction ROW_NUMBER() RANK() and DENSE_RANK() LEAD() and LAG() PARTITION BY
19. Advanced SQL
Advanced SQL Introduction Temporary Tables Table Variables Dynamic SQL Error Handling Performance Optimization

AFTER DELETE Trigger

Learn how AFTER DELETE Triggers work in SQL Server, how to create them and how to use the deleted logical table.

What is an AFTER DELETE Trigger?

An AFTER DELETE Trigger is a special SQL Server database object that automatically executes after a successful DELETE operation on a table.

It is useful when we want to perform an automatic action whenever records are deleted from a table.

  • It executes after a DELETE operation.
  • It can be used for auditing deleted records.
  • It can maintain a history of deleted data.
  • It can store information in an audit table.
  • It can perform automatic database operations.

Basic Syntax

CREATE TRIGGER TriggerName
ON TableName
AFTER DELETE
AS
BEGIN

    -- Trigger logic

END;

Example Table

Let's assume that we have a Students table.

CREATE TABLE Students
(
    StudentId INT PRIMARY KEY,
    StudentName VARCHAR(100),
    City VARCHAR(50),
    Age INT
);

Insert Sample Data

INSERT INTO Students
(
    StudentId,
    StudentName,
    City,
    Age
)
VALUES
(
    101,
    'Rahul',
    'Pune',
    21
);
INSERT INTO Students
(
    StudentId,
    StudentName,
    City,
    Age
)
VALUES
(
    102,
    'Priya',
    'Mumbai',
    22
);

Create an Audit Table

Before creating the trigger, we can create a separate table to store the details of deleted students.

CREATE TABLE DeletedStudentAudit
(
    AuditId INT IDENTITY(1,1) PRIMARY KEY,
    StudentId INT,
    StudentName VARCHAR(100),
    City VARCHAR(50),
    Age INT,
    DeletedDate DATETIME
);

Creating an AFTER DELETE Trigger

Now we create a trigger that automatically stores deleted student information in the audit table.

CREATE TRIGGER trg_StudentAfterDelete
ON Students
AFTER DELETE
AS
BEGIN

    INSERT INTO DeletedStudentAudit
    (
        StudentId,
        StudentName,
        City,
        Age,
        DeletedDate
    )
    SELECT
        StudentId,
        StudentName,
        City,
        Age,
        GETDATE()
    FROM deleted;

END;

The deleted Logical Table

SQL Server provides a special logical table named deleted inside a DELETE trigger.

The deleted logical table contains the rows that were deleted by the DELETE operation.

Logical Table Contains
deleted Rows that were deleted from the table

Performing a DELETE Operation

Now delete a student from the Students table.

DELETE FROM Students
WHERE StudentId = 101;

What Happens During DELETE?

Suppose the student record before deletion is:

StudentId = 101
StudentName = Rahul
City = Pune
Age = 21

When the following statement executes:

DELETE FROM Students
WHERE StudentId = 101;

SQL Server makes the deleted row available through the deleted logical table.

Our trigger then reads the deleted record and inserts it into the DeletedStudentAudit table.

Check Deleted Records

To check the records saved by the trigger:

SELECT *
FROM DeletedStudentAudit;

The deleted student information will be available in the audit table.

AFTER DELETE Trigger with Multiple Rows

A DELETE statement can delete multiple records at once.

DELETE FROM Students
WHERE City = 'Mumbai';

In this situation, the deleted logical table can contain multiple rows.

Therefore, trigger logic should be written using set-based operations and should not assume that only one record was deleted.

deleted Table in DELETE Trigger

During a DELETE operation:

  • deleted contains the deleted rows.
  • The deleted rows can be accessed inside the trigger.
  • The deleted information can be copied to an audit or history table.

Practical Example

A common real-world use of an AFTER DELETE Trigger is maintaining an audit or history table.

CREATE TRIGGER trg_StudentDeleteHistory
ON Students
AFTER DELETE
AS
BEGIN

    INSERT INTO DeletedStudentAudit
    (
        StudentId,
        StudentName,
        City,
        Age,
        DeletedDate
    )
    SELECT
        StudentId,
        StudentName,
        City,
        Age,
        GETDATE()
    FROM deleted;

END;
Important
  • AFTER DELETE triggers execute after a successful DELETE operation.
  • The deleted logical table contains the deleted rows.
  • A DELETE statement can affect multiple rows.
  • Trigger logic should therefore support multiple deleted records.
  • AFTER DELETE triggers are commonly used for auditing and maintaining deletion history.
Summary

An AFTER DELETE Trigger automatically executes after a successful DELETE operation. The deleted logical table provides access to the records that were deleted. AFTER DELETE Triggers are commonly used for auditing, maintaining deletion history and performing automatic database operations.