Click here to Skip to main content
15,126,670 members
Articles / Database Development / SQL Server
Posted 16 Feb 2012

Tagged as


12 bookmarked

Be Very Careful When You Write SQL Trigger

Rate me:
Please Sign up or sign in to vote.
4.83/5 (12 votes)
18 Feb 2012CPOL4 min read
Be Very Careful When You Write SQL Trigger
In many scenarios, we write triggers on database tables. Before writing a trigger, we need to understand what trigger is and how exactly it works. Because, lack of clear knowledge on triggers can ake your life difficult. Trigger is actually a procedure that runs in response of an event fired due to performing some operations on database tables. The events could be insert, update or delete. Now, the question is how the database handles the execution of a trigger when it fires?

If you write a trigger for insert operation on a table, after firing the trigger, it creates a table named “INSERTED” in the memory. Then it performs the insert operation and after that the statements inside the trigger executes. We can query the “INSERTED” table to manipulate or use the inserted row/s from the trigger.

Similarly, if you write a trigger for delete operation on a table, it creates a table in memory named “DELETED” and then deletes the row.

More importantly, you must understand how an update trigger works. After firing an update trigger, it works in the following sequence:

  1. All constraints are enforced.
  2. All declarative referential integrity (DRI) constraints are enforced (via foreign keys).
  3. The inserted and deleted tables are created in memory for use within the trigger.
  4. The triggering action (in this case the UPDATE statement) is executed.
  5. The AFTER UPDATE trigger executes.

From the above steps, you can see that no table called “UPDATED” is created. Actually on database no operation called update executes. Internally it actually deletes the rows to be updated and keeps the deleted rows in DELETED table. The updated rows that are sent to update the table are kept in INSERTED TABLE. After the old rows are backed up to the DELETED table, updated rows from INSERTED tables get inserted into the targeted table.

So, from an update trigger, we can access both INSERTED</code and <code>DELETED table though directly we may not execute any insert or delete operation. This is a very important concept for us. Here I am providing the mistakes you may make if you are not clear on this.

Consider the following trigger:

CREATE TRIGGER TriggerName ON YourTableName
if(exists(select Contact_Id from inserted where Contact_id is not null))
--Do your operation
if(exists(select Contact_Id from deleted where Contact_id is not null))
--Do your operation

Here the developer wrote the trigger for all the events on the table and expecting to do some operation if Contact_ID is inserted, deleted or updated into the table.

Now note carefully the mistakes that the developer made in this trigger. For example, an operation is executed on the table which updates some other field other than Contact_ID. Now if Contact_ID is a not null column of the table, we will never get null from INSERTED and the DELETED table. So, here even though Contact_ID is not updated, the operation of the triggers will execute.

It is not finished yet. It has more problems. The developer wrote the 2nd if condition assuming that DELETED table will be created only when trigger fires for any Delete operation on the table. But you see, as a matter of fact, this table is also available when the trigger fires for update operation.

The situation will be the worst if the developer thinks the first if statement will be successful for INSERT and UPDATE operation and 2nd if statement will be successful for DELETE operation. Note that, in reality both 1st and 2nd if statements will be successful for update operations! So, if a developer wants some code to execute for all the operations, he might make the mistake of writing the same code in both 1st and 2nd if blocks. This will in turn execute the same operation twice while any update operation is done. Doesn’t it sound very silly and surprising? Yes. But if you are not careful, these mistakes can happen anytime and can take you to hell from the heaven you are currently in.

Another Mistake:

Say you are updating 5 rows of a table with a single update statement. Then, in trigger, you are querying as follows:

DECLARE @IsPublished [bit] 
SET @IsPublished = (SELECT [IsPublished] FROM [inserted])

Here, you are expecting 1 row in the INSERTED table all the time. You may think internally SQL Server creates separated INSERTED AND DELETED tables for each of the 5 rows. But no! In reality, it will create 1 INSERTED table and 1 DELETED table. Each of the tables will contain all the 5 rows. So, the above SQL statement will return an error. You should always be careful of this.

So, while writing a trigger, keep an eye on the following points:

  1. If you write a single trigger for multiple event, be very careful to ensure that your trigger does not execute for unwanted events.
  2. When writing update trigger, always check if your desired column is updated by using IF UPDATE(ColumnName).
  3. Be very careful in querying INSERTED and DELETED table.
  4. Try to avoid cursor from the trigger.
  5. Ensure that your trigger is not creating any deadlock/Infinite loop on your database.

Wish you write error free triggers and save hours of trouble shooting!


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Mahmud Hasan
Software Developer (Senior)
Netherlands Netherlands
Software Engineer | Software Architect | System Designer | System Analyst | Team Leader | Consultant (.Net)

12 Years of Experience in the Industry.

Currently working as System Designer at CIMSOLUTIONS, Netherlands

View My Profile in LinkedIn

Comments and Discussions

QuestionRegarding 2 IFs in a Trigger Pin
Member 146112322-Oct-19 23:42
MemberMember 146112322-Oct-19 23:42 
QuestionWhat if we right Delete Query inside Delete Trigger Pin
Umendratembhare23-Aug-15 23:16
MemberUmendratembhare23-Aug-15 23:16 
QuestionGreat article Pin
Salexandersen1-Apr-14 10:03
MemberSalexandersen1-Apr-14 10:03 
GeneralMy vote of 4 Pin
sachin4dotnet3-Dec-12 23:21
Membersachin4dotnet3-Dec-12 23:21 
GeneralRe: My vote of 4 Pin
Mahmud Hasan3-Dec-12 23:23
MemberMahmud Hasan3-Dec-12 23:23 
GeneralReason for my vote of 5 Nice article. Pin
Saraf Talukder20-Feb-12 1:00
MemberSaraf Talukder20-Feb-12 1:00 
GeneralReally helpful to have a clear concept on trigger operation ... Pin
SERokon18-Feb-12 8:37
MemberSERokon18-Feb-12 8:37 
GeneralReason for my vote of 5 Very helpful Pin
Khairul_Islam18-Feb-12 6:42
MemberKhairul_Islam18-Feb-12 6:42 
GeneralNice!!! I want to share another situation like you may get ... Pin
Khairul_Islam18-Feb-12 6:40
MemberKhairul_Islam18-Feb-12 6:40 
GeneralReason for my vote of 5 Very clear explanation. Pin
S. M. Ahasan Habib18-Feb-12 6:39
professionalS. M. Ahasan Habib18-Feb-12 6:39 
GeneralVery useful stuff. Pin
Khairul_Islam18-Feb-12 6:11
MemberKhairul_Islam18-Feb-12 6:11 
GeneralGood post with very few words Pin
SERokon18-Feb-12 8:36
MemberSERokon18-Feb-12 8:36 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.