EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 360+ Courses All in One Bundle
  • Login

SQL DELETE Trigger

Home » Data Science » Data Science Tutorials » SQL Tutorial » SQL DELETE Trigger

SQL-DELETE-Trigger

Introduction to SQL DELETE Trigger

DELETE Trigger is a data manipulation language (DML) trigger in SQL. A stored procedure on a database object gets invoked automatically instead of before or after a DELETE command has been successfully executed on the said database table. DELETE Triggers are usually used in scenarios when we want to track details of data removal from a table in a separate audit table or when we want to perform cascading delete operations, like if we delete a row from table1, then it should be deleted from table2 as well.

Syntax and parameters

The basic syntax used for writing a DELETE Trigger in SQL is as follows :

Start Your Free Data Science Course

Hadoop, Data Science, Statistics & others

CREATE TRIGGER [schema_name. ] trigger_name ON table_name
{AFTER| BEFORE | INSTEAD OF } DELETE
AS
{SQL statements}

The arguments used in the above-mentioned syntax are as follows :

schema_name: schema_name here corresponds to the name of the schema where the new

A delete trigger will be created. The schema name is optional, but when we do not mention the schema_name, the trigger gets created in the default schema.

trigger_name: trigger_name is the name of the new delete trigger which is being created.

table_name: table_name is the name of the database table on which the new A delete trigger will be created.

AFTER | BEFORE | INSTEAD OF: This argument is to register the time of DELETE trigger invocation concerning the execution of the DELETE statement.

Popular Course in this category
Sale
JDBC Training (6 Courses, 7+ Projects)6 Online Courses | 7 Hands-on Projects | 37+ Hours | Verifiable Certificate of Completion | Lifetime Access
4.5 (8,929 ratings)
Course Price

View Course

Related Courses
PHP Training (5 Courses, 3 Project)Windows 10 Training (4 Courses, 4+ Projects)SQL Training Program (7 Courses, 8+ Projects)PL SQL Training (4 Courses, 2+ Projects)Oracle Training (14 Courses, 8+ Projects)

SQL statements: SQL statements are a set of SQL operations that form the body of a DELETE trigger.

Having discussed the syntax and parameters used for creating DELETE triggers in SQL, let us try a few examples to understand it in great detail.

Examples of SQL DELETE Trigger

To illustrate DELETE Triggers’ work in SQL, let us create two dummy tables called students and students_audit, respectively.

CREATE TABLE students(
roll_no int NOT NULL PRIMARY KEY,
student_name VARCHAR(255),
degree_major VARCHAR(255) NOT NULL,
degree_year VARCHAR(255),
society VARCHAR(255)
);

SQL DELETE Trigger output 1

Having created the student’s table. Let us insert a few records in it to work with.

INSERT INTO [practice_db].[dbo].[students] ([roll_no] ,[student_name] ,[degree_major] ,[degree_year] ,[society])
VALUES
(1,'Mohith K','Computer Science Engineering','IV','Dramatics'),
(2,'Ayesha Khan','Electrical Engineering','I','Music'),
(3,'Kylie Green','Computer Science Engineering','III','Choreography'),
(4,'Alisha Rojer','Chemical Engineering','III','Music'),
(5,'Andy Bernard','Geosciences','IV','Dramatics')
GO

SQL DELETE Trigger output 2

Next, let us create the students_audit table, which is similar to the student’s table but with two additional columns.

CREATE TABLE students_audit(
roll_no int NOT NULL PRIMARY KEY,
student_name VARCHAR(255),
degree_major VARCHAR(255) NOT NULL,
degree_year VARCHAR(255),
society VARCHAR(255),
deleted_by VARCHAR(50),
deleted_at DATETIME
);

SQL DELETE Trigger output 3

Let’s leave this table empty for the time being.

Example #1

Create a DELETE Trigger on the student’s table that deletes records from the student’s table and insert the deleted records with servername and time of deletion on a separate table called “students_audit”.

Code:

CREATE TRIGGER AfterDELETETrigger on students
AFTER DELETE
AS DECLARE
@roll_no INT,
@student_name VARCHAR(255),
@degree_major VARCHAR(255),
@degree_year VARCHAR(255),
@society VARCHAR(255);
SELECT @roll_no = d.roll_no FROM DELETED d;
SELECT @student_name = d.student_name FROM DELETED d;
SELECT @degree_major = d.degree_major FROM DELETED d;
SELECT @degree_year = d.degree_year FROM DELETED d;
SELECT @society = d.society FROM DELETED d;
INSERT INTO students_audit(
[roll_no] ,[student_name] ,[degree_major] ,[degree_year] ,[society] ,[Deleted_by] ,[Deleted_at])
VALUES (@roll_no,
@student_name,
@degree_major,
@degree_year,
@society,
CAST( SERVERPROPERTY('ServerName') AS VARCHAR(50)),
GETDATE());
GO

SQL DELETE Trigger output 4

The query was executed successfully. The newly created AfterDELETETrigger has been mentioned under the Triggers head in the object explorer.

SQL DELETE Trigger output 5

Now let us check if the “AfterDELETETrigger” serves the intended purpose. Here is a DELETE statement on the student’s table that tries to delete a row with roll_no = ‘3’.

DELETE FROM students
WHERE roll_no = '3';

SQL DELETE Trigger output 6

Two rows got affected. That’s true, one row of the student’s table got removed, and one row got inserted in the students_audit table. Let’s check for ourselves using a SELECT statement.

SELECT * FROM students_audit;

output 7

The row with roll_no = ‘3’ has been successfully inserted in the students_audit table.

Let’s try one more DELETE statement. Here, we are deleting one or more rows in the student’s table where the student belongs to ‘Dramatics’ and has a degree_major starting with ‘Geo’.

DELETE FROM students
WHERE society = 'Dramatics' AND degree_major LIKE 'Geo%';

output 8

Similar to the previous query, we have successfully deleted and inserted the concerned row from(in) the students and students_audit table respectively.

SELECT * FROM students;
SELECT * FROM students_audit;

output 9

Example #2

Create a delete trigger that, on executing a delete statement on the student’s table, does not delete the row from it but instead deletes it from the students_audit table.

Code:

CREATE TRIGGER InsteadDELETETrigger
ON students
INSTEAD OF DELETE
AS
DELETE FROM students_audit
WHERE roll_no IN(SELECT deleted.roll_no FROM deleted)
GO

output 10

The trigger has been successfully created. It is mentioned under the triggers head of the student’s table in object explorer.

output 11

To undo the work of the AfterDELETETrigger, let us insert back the following row in the student’s table (just for the sake of this example).

INSERT INTO [practice_db].[dbo].[students] ([roll_no] ,[student_name] ,[degree_major] ,[degree_year] ,[society])
VALUES
(3,'Kylie Green','Computer Science Engineering','III','Choreography')
GO

output 12

The present status of students and students_audit table is as follows:

SELECT * FROM students;
SELECT * FROM students_audit;

output 13

In the previous steps, we have created the ‘InsteadDELETETrigger’. Let’s check its functionality by executing a DELETE statement on the student’s table.

DELETE FROM students
WHERE society = 'Choreography';

output 14

Two rows got affected, but as intended, the row with society = ‘Choreography’ has been successfully deleted from the students_audit table instead of the student’s table.

SELECT * FROM students;
SELECT * FROM students_audit;

output 15

Conclusion

DELETE Trigger is a DDL trigger that gets fired automatically once a DELETE statement has been successfully on a database object.

Recommended Articles

This is a guide to SQL DELETE Trigger. Here we discuss the Basic syntax used for writing a DELETE Trigger along with the Examples. You may also have a look at the following articles to learn more –

  1. SQL ORDER BY DATE
  2. SQL Table Partitioning
  3. SQL NOT Operator
  4. SQL ORDER BY Ascending

All in One Data Science Bundle (360+ Courses, 50+ projects)

360+ Online Courses

50+ projects

1500+ Hours

Verifiable Certificates

Lifetime Access

Learn More

0 Shares
Share
Tweet
Share
Primary Sidebar
SQL Tutorial
  • Functions
    • SQL Date Function
    • SQL String Functions
    • SQL Compare String
    • Timestamp to Date in SQL
    • SQL Window Functions
    • SQL Timestamp
    • SQL TO_DATE()
    • SQL DATEADD()
    • SQL DATEDIFF()
    • SQL HOUR()
    • SQLite?functions
    • ANY in SQL
    • LIKE Query in SQL
    • SQL NOT NULL
    • SQL NOT IN
    • SQL MAX()
    • SQL MIN()
    • SQL SUM()
    • SQL COUNT
    • SQL identity
    • SQL DELETE Trigger
    • SQL Declare Variable
    • SQL Text Search
    • SQL COUNT DISTINCT
    • SQL TEXT
    • SQL Limit Order By
    • BETWEEN in SQL
    • LTRIM() in SQL
    • TOP in SQL
    • SQL Select Top
    • Merge SQL
    • SQL TRUNCATE()
    • SQL UNION
    • SQL ALL
    • SQL INTERSECT
    • SQL Alias
    • SQL Server Substring
    • CUBE in SQL
    • SQL RANK()
    • SQL MOD()
    • SQL CTE
    • SQL LAG()
    • SQL MID
    • SQL avg()
    • SQL WEEK
    • SQL DELETE
    • SQL DATEPART()
    • SQL DECODE()
    • SQL DENSE_RANK()
    • SQL NTILE()
    • SQL NULLIF()
    • SQL Stuff
    • SQL Ceiling
    • SQL EXISTS
    • SQL LEAD()
    • SQL COALESCE
    • SQL BLOB
    • SQL ROW_NUMBER
    • SQL Server Replace
    • SQL Server Permission
    • T-SQL INSERT
    • SQL Ranking Function
  • Basic
    • What is SQL
    • Careers in SQL
    • Careers in SQL Server
    • IS SQL Microsoft?
    • SQL Management Tools
    • What is SQL Developer
    • Uses of SQL
    • How to Install SQL Server
    • What is SQL Server
    • SQL Server Versions
    • SQL Case Insensitive
    • SQL Expressions
    • Database in SQL
    • SQL Data Types
    • SQL Keywords
    • Composite Key in SQL
    • SQL WAITFOR
    • SQL Constraints
    • Transactions in SQL
    • First Normal Form
    • SQL Server Data Types
    • SQL Administration
    • SQL Variables
    • SQL Enum
    • SQL GROUP BY WHERE
    • SQL ROW
    • SQL EXECUTE
    • SQL EXCLUDE
    • SQL Performance Tuning
    • SQL UUID
    • Begin SQL
    • SQL Update Join
    • Cheat sheet SQL
  • Operators
    • SQL Operators
    • SQL Arithmetic Operators
    • SQL Logical Operators
    • SQL String Operators
    • Ternary Operator in SQL
  • Commands
    • SQL Commands
    • sqlplus set commands
    • SQL Alter Command
    • SQL Commands Update
    • SQL DML Commands
    • SQL DDL Commands
    • FETCH in SQL
  • Clause
    • SQL Clauses
    • SQL IN Operator
    • SQL LIKE Clause
    • SQL NOT Operator
    • SQL Minus
    • SQL WHERE Clause
    • SQL with Clause
    • SQL HAVING Clause
    • GROUP BY clause in SQL
    • SQL GROUP BY DAY
    • ORDER BY Clause in SQL
    • SQL ORDER BY CASE
    • SQL ORDER BY DESC
    • SQL ORDER BY DATE
    • SQL ORDER BY Alphabetical
    • SQL ORDER BY Ascending
    • SQL Order by Count
    • SQL GROUP BY Month
    • SQL GROUP BY Multiple Columns
    • SQL GROUPING SETS
  • Queries
    • SQL Insert Query
    • SQL SELECT Query
    • SQL SELECT RANDOM
    • SQL Except Select
    • SQL Subquery
    • SQL SELECT DISTINCT
    • SQL WITH AS Statement
  • Keys
    • SQL Keys
    • Primary Key in SQL
    • Foreign Key in SQL
    • Unique Key in SQL
    • Alternate Key in SQL
    • SQL Super Key
  • Joins
    • Join Query in SQL
    • Types of Joins in SQL
    • Types of Joins in SQL Server
    • SQL Inner Join
    • SQL Join Two Tables
    • SQL Delete Join
    • SQL Left Join
    • LEFT OUTER JOIN in SQL
    • SQL Right Join
    • SQL Cross Join
    • SQL Outer Join
    • SQL Full Join
    • SQL Self Join
    • Natural Join SQL
    • SQL Multiple Join
  • Advanced
    • SQL Formatter
    • SQL Injection Attack
    • Aggregate Functions in SQL
    • IF ELSE Statement in SQL
    • SQL CASE Statement
    • SQL While Loop
    • SQL BIGINT
    • SQL Crosstab
    • SQL Wildcard Character
    • SQLAlchemy Filter
    • SQLAlchemy create_engine
    • SQL INSTR()
    • SQL now
    • SQL synonyms
    • SQLite?export to csv
    • What is Procedure in SQL
    • Stored Procedure in SQL?
    • SQL Server Constraints
    • SQL DELETE ROW
    • Column in SQL
    • Table in SQL
    • SQL Virtual Table
    • SQL Merge Two Tables
    • SQL Table Partitioning
    • SQL Temporary Table
    • SQL Clone Table
    • SQL Rename Table
    • SQL LOCK TABLE
    • SQL Clear Table
    • SQL DESCRIBE TABLE
    • SQL Mapping
    • Cursors in SQL
    • AND in SQL
    • Wildcard in SQL
    • SQL FETCH NEXT
    • SQL Views
    • SQL Delete View
    • Triggers in SQL
    • SQL UPDATE Trigger
    • SQL AFTER UPDATE Trigger
    • SQL Update Statement
    • SQL DROP TRIGGER
    • Types of SQL Views
    • SQL Port
    • SQL Clustered Index
    • SQL COMMIT
    • Distinct Keyword in SQL
    • PARTITION BY in SQL
    • SQL Set Operators
    • SQL UNION ALL
    • Metadata in SQL
    • SQL Bulk Insert
    • Array in SQL
    • SQL REGEXP
    • JSON in SQL
    • SQL For loop
    • EXPLAIN in SQL
    • ROLLUP in SQL
    • Escape Character SQL
    • SQL Cluster
    • SQL Backup
    • SQL Pattern Matching
    • SQL Users
    • ISNULL SQL Server
    • SQL pivot
    • SQL Import CSV
    • SQL if then else
    • SQL ignore-case
    • SQL Matches
    • SQL Search String
    • SQL Column Alias
    • SQL extensions
    • SQL Substring Function
    • Charindex SQL
  • NoSQ
    • NoSQL Databases List
    • NoSQL Injection
    • NoSQL vs SQL Databases
  • Interview Questions
    • SQL Interview Questions
    • Advance SQL Interview Questions
    • SQL Joins Interview Questions
    • SQL Server Interview Questions

Related Courses

JDBC Training Course

PHP course

Windows 10 Training

SQL Course Training

PL/SQL Certification Courses

Oracle Certification Courses

Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Live Classes
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Database Management
  • Machine Learning
  • All Tutorials
Certification Courses
  • All Courses
  • Data Science Course - All in One Bundle
  • Machine Learning Course
  • Hadoop Certification Training
  • Cloud Computing Training Course
  • R Programming Course
  • AWS Training Course
  • SAS Training Course

© 2022 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA
Free Data Science Course

Hadoop, Data Science, Statistics & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA
Free Data Science Course

Hadoop, Data Science, Statistics & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

Let’s Get Started

By signing up, you agree to our Terms of Use and Privacy Policy.

Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more

EDUCBA Login

Forgot Password?

By signing up, you agree to our Terms of Use and Privacy Policy.

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

Special Offer - JDBC Training Course Learn More