Click here to Skip to main content
15,889,693 members
Articles / Database Development / MySQL

What is a Database Trigger?

Rate me:
Please Sign up or sign in to vote.
4.47/5 (5 votes)
14 Aug 2019MIT6 min read 14.1K   4   1
What is a Database Trigger?

Introduction

A database trigger is a special stored procedure that is run when specific actions occur within a database. Most triggers are defined to run when changes are made to a table’s data. Triggers can be defined to run instead of or after DML (Data Manipulation Language) actions such as INSERT, UPDATE, and DELETE.

Triggers help the database designer ensure certain actions, such as maintaining an audit file, are completed regardless of which program or user makes changes to the data.

The programs are called triggers since an event, such as adding a record to a table, fires their execution.

Triggers and their implementations are specific to database vendors. In this article, we’ll focus on Microsoft SQL Server; however, the concepts are the same or similar in Oracle and MySQL.

Note: All the examples for this lesson are based on Microsoft SQL Server Management Studio and the AdventureWorks2012 database. You can get started using these free tools using my Guide Getting Started Using SQL Server.

Events

The triggers can occur AFTER or INSTEAD OF a DML action. Triggers are associated with the database DML actions INSERT, UPDATE, and DELETE. Triggers are defined to run when these actions are executed on a specific table.

AFTER Triggers

Once the DML actions, such as an INSERT completes, the AFTER trigger executes. Here are some key characteristics of AFTER triggers:

  • After triggers are run after a DML action, such as an INSERT statement and any ensuing referential cascade actions and constraint checks have run.
  • You can’t cancel the database action using an AFTER trigger. This is because the action has already completed.
  • One or more AFTER triggers per action can be defined on a table, but to keep things simple, I recommend only defining one.
  • You can’t define AFTER triggers on views.

INSTEAD OF Triggers

INSTEAD OF triggers, as their name implies, run in place of the DML action which caused them to fire. Items to consider when using INSTEAD OF triggers include:

  • An INSTEAD OF trigger overrides the triggering action. If an INSTEAD OF trigger is defined to execute on an INSERT statement, then once the INSERT statement attempts to run, control is immediately passed to the INSTEAD OF trigger.
  • At most, one INSTEAD OF trigger can be defined per action for a table. This makes sense, as if you had to “INSTEAD OF” triggers for an insert, which one should run?

Special Database Objects

Triggers use two special database objects, INSERTED and DELETED, to access rows affected by the database actions. Within the scope of a trigger, the INSERTED and DELETE objects have the same columns as the trigger’s table.

The INSERTED table contains all the new values; whereas, the DELETED table contains old values. Here is how the tables are used:

  • INSERT – Use the INSERTED table to determine which rows were added to the table.
  • DELETE – Use the DELETED table to see which rows were removed from the table.
  • UPDATE – Use the INSERTED table to inspect the new or updated values and the DELETED table to see the values prior to update.

Definition

A trigger is defined for a specific table and one or more events. In most database management systems, you can only define one trigger per table.

Below is an example trigger from the AdventureWorks2012 database.

Example AFTER INSERT trigger

You’ll notice the syntax for a trigger is very similar to that of a stored procedure. In fact, the trigger uses the same language to implement its logic as do stored procedures. In MS SQL, this is T-SQL; whereas in Oracle, it is PL/SQL.

Here are some important parts to a trigger:

  1. The CREATE statement – It defines which table is associated with the trigger. In addition, this statement is used to specify when the trigger executes (e.g., after insert).
  2. The actual program. In the example, this program runs whenever one or more rows are inserted into the WorkOrder table.
  3. Special database objects – Triggers use specially defined databases objects such as INSERTED, or DELETED to access records affected by the database action.
  4. In this example, the trigger is using the INSERTED object to gain access to the newly created rows. The INSERT statement is used to table those rows and add them to a history table.

Uses for Triggers

Here are some common uses for triggers:

Complex Auditing

You can use triggers to track changes made to tables. In our example above, changes made to the WorkOrder table are recorded in a TransactionHistory table.

Typically when creating audit trails, you’ll use AFTER triggers.

You may think this is redundant, as many changes are logged in the databases journals, but the logs are meant for database recovery and aren’t easily accessible by user programs. The TransactionHistory table is easily referenced and can be incorporated into end user reports.

Enforce Business Rules

Triggers can be used to inspect all data before a DML action is performed. You can use INSTEAD OF triggers to “intercept” the pending DML operation, apply any business rules, and ultimately complete the transaction.

An example business rule may be that a customer status is defined as:

  • Gold – Purchases over $1,000,000 in the past 12 months
  • Silver – Purchase of $500,000 to $1,000,000 in the past 12 months
  • Bronze – All other purchase levels

An INSTEAD OF trigger could be defined to check the customer status each time a customer record is added or modified. The status check would involve creating a sum of all the customers’ purchases and ensuring the new status corresponds with the sum of the last 12 months of purchases.

Derive Column Values

Triggers can be used to calculate column values. For instance, for each customer, you may wish to maintain a TotalSales column on the customer record. Of course, for this to remain accurate, it would have to be updated every time a sales was made.

This could be done using an AFTER trigger on INSERT, UPDATE, and DELETE statements for the Sales table.

Triggers are Tricky!

In general, my advice is to avoid using triggers unless absolutely necessary.

You should avoid using triggers in place of built in features. For instance, rather than rely on triggers to enforce referential integrity, you’re better off using relationships.

Here are some reasons why I shy away from them:

  1. They can be hard to troubleshoot.
  2. Triggers can cause other triggers to fire. Two Tables, A and B, both have an AFTER UPDATE trigger. If the AFTER UPDATE trigger on Table A updates Table B, then updating Table A causes its trigger and then B’s trigger to Fire.
  3. You have to be sure you don’t create a trigger storm! Can you imagine if Table B, for some reason, updated Table A? Now you have a circular reference… Boom!
  4. I try to move as much logic into Stored Procedures and have applications make changes to the database through them rather than straight up SQL statements.

The post What is a Database Trigger? appeared first on Essential SQL.

This article was originally posted at https://www.essentialsql.com/what-is-a-database-trigger

License

This article, along with any associated source code and files, is licensed under The MIT License


Written By
Easy Computer Academy, LLC
United States United States
Hello my name is Kris. I’m here because I am passionate about helping non-techie people to overcome their fear of learning SQL.

I know what it is like to not know where to start or whether the time spent learning is worth the effort. That is why I am here to help you to:
- Get started in an easy to follow step-by-step manner.
- Use your time wisely so you focus on what is important to learn to get the most value from your time.
- Answer your questions. Really! Just post a comment and I’ll respond. I’m here to help.

It wasn’t long ago that I was helping a colleague with some reporting. She didn’t know where to start and soon got overwhelmed and lost as she didn’t know SQL.

I felt really bad, as she was under pressure to get some summary information to her boss, the built-in reports were falling short, and to make them better would require her to know SQL. At that time that seemed impossible! It in dawned on me, it doesn’t have to be that way.

Then I discovered a way for anyone with the desire to easily learn SQL. I worked with my co-worker, started to teach her what I learned and soon she was able to write reports and answer her boss’ questions without getting stressed or ploughing hours into manipulating data in Excel.

It hasn’t always been easy. Sometimes the information seems abstract or too conceptual. In this case I’ve found out that a visual explanation is best. I really like to use diagrams or videos to explain hard-to-grasp ideas.

Having video, pictures, and text really help to reinforce the point and enable learning.

And now I want to help you get the same results.

The first step is simple, click here http://www.essentialsql.com/get-started-with-sql-server/

Comments and Discussions

 
QuestionVote 5 Pin
EhabAhmed23-Aug-19 4:34
EhabAhmed23-Aug-19 4:34 

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.