1. Back To Blog

SQL Server Interview Question and answers-Triggers, Instead of triggers, after triggers, inserted and deleted tables?

Triggers are special kind of stored procedure. They can be executed after or before data modification happens on a table. There are two types of triggers "Instead of triggers" and "After triggers".


"Instead of triggers" executes prior to data modification while "after trigger" executes after data modification.

 

In what scenarios will you use instead of trigger and after trigger?


You will use "INSTEAD trigger" to take alternative actions before the update happens.

Some of the uses of instead of trigger's are:-

  • Reject updates which are not valid.
  • Take some alternative action if any error occurs.
  • To implement cascading deletes. For instance you want to delete a customer record. But in order to delete the customer record you also have to delete address records. So you can create a instead of trigger which will first delete the address table before executing delete on customer table.


     While "AFTER trigger" is useful when you want to execute trigger logic after the data has been updated.

    Some uses of after triggers are:-

  • For recording Audit trail where you want new and old values to be inserted in to audit table.
  • Updating values after the update has happened. For instance in a sales table if number of products and per product is inserted, you can create an after trigger which will calculate the total sales amount using these two values.


    What are inserted and deleted tables?

    During triggers we sometimes need old and new values. Insert and deleted tables are temporary tables created by SQL server itself which have new and old values. Inserted tables have one record for newly added data and deleted table has one record of the old version of the data.

    So for instance let's say we add a new record called as "Shiv". The inserted table will have "Shiv" and deleted table will have nulls because the record did not exist. Now let's say some user updates "Shiv" to "Raju". Then inserted table will have "Raju" and deleted tables will have "Shiv".

  • Taken from the best selling SQL Server interview question book, you can see more about the book by clicking on SQL Server interview questions book .

    Here is our latest 20+ SQL Interview Questions and Answers video :-

    See for more stuffs on SQL server interview questions | Click to view more from authors on SQL server interview questions

  • Shiv Prasad Koirala

    Visit us @ www.questpond.com or call us at 022-66752917... read more

    We are on Social