×

Trigger in SQL

In this article, we will learn about the concept of trigger in SQL and its implementation with the help of an example.

A Trigger in Structured Query Language is a set of procedural statements executed automatically when there is any feedback to certain events on the table in the database. Triggers are used to protect the integrity of the data in the database.

Let’s see the following situation to understand the concept of trigger in SQL:  

Suppose Supriya is the information technology manager in a multinational company. When the record of a new employee is entered into the database, she has to send the 'Congratulations' message to each new employee. If there are five or six employees, Supriya can do it manually, but if the number of new Employees is more than the thousand, then in such a condition, she has to use the trigger in the database.

Thus, Supriya has to create the trigger in the table, which will automatically send a 'Congratulations' message to the new employees once their record is inserted into the database.

The trigger is always executed with the specific table in the database. If we remove the table, all the triggers associated with that table are also deleted automatically.

Triggers in the Structured Query Language are called only before the events have occurred or after the events have occurred.

Only three events occur in the trigger before or after the events are the Insert events, the Update events, or the Delete events.

1. INSERT Event: Insert event occurs whenever a new record is inserted into the table.

2. UPDATE Event: An update event occurs whenever the existing records are updated in the table.

3. DELETE Event: The Delete event occurs whenever the record is deleted from the table.

Types of triggers in the Structured Query Language

Following are the six types of triggers used in the Structured Query Language:

1. AFTER INSERT Trigger:

The after insert trigger is invoked in SQL after the records are inserted in the table.

2. AFTER UPDATE Trigger:

The after update trigger is invoked in SQL after the existing records in the table are updated.

3. AFTER DELETE Trigger:

The after delete trigger is invoked in SQL after the record are deleted from the table.

4. BEFORE INSERT Trigger:

The before insert trigger is invoked in SQL before the records are inserted in the table.

5. BEFORE UPDATE Trigger:

The before update trigger is invoked in SQL before the existing records in the table are updated.

6. BEFORE DELETE Trigger:

The before delete trigger is invoked in SQL before the record are deleted from the table.

Syntax of trigger in SQL:

CREATE TRIGGER Trigger_Name  

[BEFORE | AFTER]  [Insert | Update | Delete] 

ON [Table_Name] 

[FOR EACH ROW | FOR EACH COLUMN] 

AS 

Set of SQL Statement
  • In the trigger syntax, we have to define the trigger name just after the CREATE TRIGGER keyword in the syntax.
  • After the trigger name, we have to define which trigger we want to invoke, the before trigger or the after trigger keyword with the event name.
  • Then, we have to mention the table name on which trigger is occurred.
  • After the table name, we must define the trigger on the row-level or the column-level trigger.
  • And in the end, we have to write the SQL statement that acts on the events occurring.

Example of trigger in SQL

To understand the concept of trigger in the SQL, we have to create a table on which trigger is to be executed.

The following query creates the Student table in the SQL database.

CREATE TABLE Student(

Student_rollno INT NOT NULL PRIMARY KEY,

FirstName varchar(40),

English_Marks INT,

Physics_Marks INT,

Chemistry_Marks INT,

Biology_Marks INT,

Maths_Marks INT,

Total_Marks INT,

Percentage INT);

The following query shows the structure of the Student table:

DESC Student;

FieldTypeNULLKeyDefaultExtra
Student_RollNoINTNOPRINULL
First_NameVarchar(40)YESNULL
English_MarksINTYESNULL
Physics_MarksINTYESNULL
Chemistry_MarksINTYESNULL
Biology_MarksINTYESNULL
Maths_MarksINTYESNULL
Total_MarksINTYESNULL
PercentageINTYESNULL

The following query fires the trigger before the insertion of the student record in the table:

CREATE TRIGGER Student _Marks  

BEFORE INSERT 

ON 

Student 

FOR EACH ROW 

SET new.Total_Marks = new.English_Marks + new.Physics_Marks + new.Chemistry_Marks + new.Biology_Marks + new.Maths_Marks,   

new.Percentage = ( new.Total_Marks / 500) * 100;

The following queries insert the record into the Student table.

INSERT INTO Student (Student_RollNo, First_Name, English_Marks, Physics_Marks, Chemistry_Marks,Biology_Marks, Maths_Marks, Total_Marks, Percentage) VALUES ( 1, ‘Raman’, 90, 80, 75, 70 ,92, 0, 0);  

To check the output of the above INSERT statement, you have to type the following SELECT statement:

SELECT * FROM Student

Output:

Student_RollNoFirst_NameEnglish_Marks  Physics_Marks  Chemistry_Marks  Biology_Marks  Maths_Marks  Total_Marks  Percentage
1Raman908075709240781

Advantages of Triggers in SQL

Following are the three main advantages of triggers in Structured Query Language:

  1. SQL provides an alternate way to maintain the data and referential integrity in the tables.
  2. Triggers help in executing the scheduled tasks automatically.
  3. They catch the errors in the database layer of various businesses.
  4. They allow the database users to validate values before inserting and updating.

Disadvantages of Triggers in SQL

Following are the main disadvantages of triggers in Structured Query Language:

  1. They are not compiled.
  2. It is not possible to find and debug the errors in triggers.
  3. If we use the complex code in the trigger, it makes the application run slower.
  4. Trigger increases the high load on the database system.

Related Topics

SQL SELECT AVG

In this tutorial, we will learn about the aggregate function name avg() function concept in SQL with the help of examples. The AVG() function is one of the aggregate functions in...

3 minutes read.

SQL SELECT MAX

The SQL Max() function is an aggregate function in SQL. This function returns the values which are greater in the condition. The condition may be a number, or it may...

5 minutes read.

Where Condition in SQL

WHERE clause is used with the Data Manipulation Language Command in SQL, the Data Manipulation Language commands are the SELECT statement, UPDATE statement, and DELETE statement. WHERE clause condition is an...

5 minutes read.

SQL SET Keyword

This article will provide you a good understanding of the Set keyword in Structured Query Language. What is the SET keyword? The SET keyword is used to specify values for the variables....

3 minutes read.

SQL INSERT Table

In this tutorial, we will help you to understand and learn how to add records to the table in SQL with the help of examples. SQL INSERT query is used to...

5 minutes read.

SQL Aggregate Functions

In this tutorial, we will learn and understand the SQL Aggregate Functions concept with the help of examples. SQL Aggregate Function is a function used to perform calculation operations on one...

4 minutes read.

Nth highest salary

The most common and important question asked in interviews that how we can find the Nth highest salary in a table (2nd highest salary, 3rd highest salary, or Nth highest...

6 minutes read.

SQL SELECT Statement

The SQL SELECT statement is used to retrieve the data from the tables. We can also retrieve the selected records from the table using the query condition. The SQL SELECT...

5 minutes read.

SQL SELECT LIKE Operator

The SQL SELECT LIKE Operator tutorial helps us understand how to use the LIKE operator in the SELECT query with examples. The SQL SELECT LIKE Operator retrieves the records from the...

4 minutes read.

Save Point in SQL

In SQL, the classification is done into 4 languages. They are Data Definition Language (DDL)Data Manipulation Language (DML)Transaction Control Language (TCL)Data Control Language (DCL) Save Point falls under the Transaction Control Language....

4 minutes read.

SQL Syntax

In this tutorial, we will help you understand about the different SQL Syntax concepts with the help of an example. Every Structured Query Language starts with Keywords like select, insert, update,...

5 minutes read.

SQL Cloning Tables

Cloning a Table: To create a copy of the table. To perform the operations, without affecting the actual table. Steps for creating a Cloning Table: Step 1: Empty Table Creation The syntax for Creating...

3 minutes read.

SQL FOREIGN KEY

In this article, we will learn about the FOREIGN KEY constraints and how to define a FOREIGN KEY constraint to build the relationship between two tables. In a Relational Databases Management...

4 minutes read.

GROUP BY vs ORDER BY

The GROUP BY clause and ORDER BY clause in SQL are used to arrange data obtained by SQL queries. The important difference between the GROUP BY clause and ORDER BY...

4 minutes read.

SET Operators in SQL

The operator used to join or combine two queries is none other than SET operators. Operators categorized into SET operators are as follows: UNION Operator.UNION ALL’ Operator.INTERSECT Operator.MINUS Operator. Rules to be...

8 minutes read.

Grant Command in SQL

What is DCL (Data Control Language)? Data Control Language (DCL) is a computer programming language with syntax intended to manage access to data kept in databases. It is a part of...

3 minutes read.

How to use GROUP BY clause in SQL

In this SQL article, we will learn about the GROUP BY clause and how to use it in SQL. We will also discuss using the GROUP BY clause with the...

6 minutes read.

SQL Data Definition Language

Data definition language directly effects on the structure/schema of the database. CREATE, ALTER, DROP are the commands of DDL.CREATE: Creates new database, table, or view of table.ALTER: Modifies the database or...

3 minutes read.

SQL INSERT INTO Statement

SQL INSERT INTO statement adds data to the newly created tables or existing tables. We can add single records or multiple records in a table by using this query. There are...

3 minutes read.

SQL Comparision Operator

The Comparison Operator compares different data of the Structured Query Language table and checks whether the data are the same, less than, greater than, less than, or greater than equal....

14 minutes read.