Download as pdf or txt
Download as pdf or txt
You are on page 1of 15

TRIGGERS

Trigger is a set of SQL statements that reside in system memory with unique names. It is a specialized
category of stored procedure that is called automatically when a database server event occurs. Each
trigger is always associated with a table.

A trigger is called a special procedure because it cannot be called directly like a stored procedure.

An Event can be:

DML statements: Insert ,Update Delete

DDL statements: Create, Alter , Drop


Database Operations: LOGON ,LOGOFF, SHUTDOWN

Types of triggers:
Row-Level Trigger: It is a trigger, which is activated for each row by a triggering statement such as
insert, update, or delete. For example, if a table has inserted, updated, or deleted multiple rows, the
row trigger is fired automatically for each row affected by the insert, update, or delete statement.

Statement-Level Trigger: It is a trigger, which is fired once for each event that occurs on a table
regardless of how many rows are inserted, updated, or deleted.

SYNTAX
CREATE TRIGGER trigger_name

(AFTER | BEFORE) (INSERT | UPDATE | DELETE)

ON table_name FOR EACH ROW

BEGIN

--variable declarations

--trigger code

END;

Example
CREATE TABLE student (

id INT PRIMARY KEY AUTO_INCREMENT,

name VARCHAR(255),

marks INT,

percentage DECIMAL(5,2)

);

-- Create trigger to calculate percentage

DELIMITER //

CREATE TRIGGER calculate_percentage


BEFORE INSERT ON student

FOR EACH ROW

SET NEW.percentage = (NEW.marks / 100) * 100;

//

DELIMITER ;

INSERT INTO student (name, marks) VALUES ('John Doe', 75);

TYPES OF TRIGGER ;

There are three type of trigger in SQL server but in MYSQL there are only two types that are given
below:

 DML(data manipulation language)

 DDL(data definition language)

 LOGON

DATA MANIPULATION LANGUAGE:

DML triggers are fired in response to DML events like INSERT, UPDATE, and DELETE statements in the
user's table or view. It can also be executed in response to DML-like operations performed by system-
defined stored procedures.

The DML triggers can be classified into two types:

 After trigger

 Instead of trigger

 Before trigger

AFTER TRIGGER:

After trigger fires, when SQL Server completes the triggering action successfully, that fired it. Generally,
this trigger is executed when a table completes an insert, update or delete operations. It is not
supported in views. Sometimes it is known as FOR triggers.

We can classify this trigger further into three types:

 After insert

 After update

 After delete

Example: When we insert data into a table, the trigger associated with the insert operation on that
table will not fire until the row has passed all constraints, such as the primary key constraint. SQL
Server cannot fire the AFTER trigger when the data insertion failed.

The following is illustration of the After Triggers syntax in SQL Server:

CREATE TRIGGER schema_name.trigger_name

ON table_name

AFTER {INSERT | UPDATE | DELETE}

AS
BEGIN

-- Trigger Statements

-- Insert, Update, Or Delete Statements

END

INSTEAD OF TRIGGER:

Instead of Trigger fires before SQL Server begins to execute the triggering operation that triggered it. It
means that no condition constraint check is needed before the trigger runs. As a result, even if the
constraint check fails, this trigger will fire. It is the opposite of the AFTER trigger. We can create the
INSTEAD OF triggers on a table that executes successfully but doesn't contain the table's actual insert,
update, or delete operations.

We can classify this trigger further into three types:

 INSTEAD OF INSERT Trigger

 INSTEAD OF UPDATE Trigger

 INSTEAD OF DELETE Trigger

Example: When we insert data into a table, the trigger associated with the insert operation on that
table will fire before the data has passed all constraints, such as the primary key constraint. SQL Server
also fires the Instead of Trigger if the data insertion fails.

The following is an illustration of the Instead of Triggers syntax in SQL Server:

CREATE TRIGGER schema_name.trigger_name

ON table_name

INSTEAD OF {INSERT | UPDATE | DELETE}

AS

BEGIN

-- trigger statements

-- Insert, Update, or Delete commands

END

BEFORE TRIGGER :

Before Trigger fires before SQL Server begins to execute the triggering operation that triggered it. It
means that no condition constraint check is needed before the trigger runs. As a result, even if the
constraint check fails, this trigger will fire. It is the opposite of the AFTER trigger.

We can classify this trigger further into three types:

 Before insert

 Before update

 Before delete

Syntax:

CREATE TRIGGER schema_name.trigger_name


ON table_name

BEFORE {INSERT | UPDATE | DELETE}

AS

BEGIN

-- Trigger Statements

-- Insert, Update, Or Delete Statements

END

LOGON TRIGGER:

Logon triggers are fires in response to a LOGON event. The LOGON event occurs when a user session is
generated with an SQL Server instance, which is made after the authentication process of logging is
completed but before establishing a user session. As a result, the SQL Server error log will display all
messages created by the trigger, including error messages and the PRINT statement messages. If
authentication fails, logon triggers do not execute. These triggers may be used to audit and control
server sessions, such as tracking login activity or limiting the number of sessions for a particular login.

DDL TRIGGER (Data Defination Language):

DDL triggers respond to DDL events like CREATE, ALTER, DROP, GRANT, DENY, REVOKE, or UPDATE
STATISTICS. For example, you can define a DDL trigger that records CREATE or ALTER TABLE
operations.DDL trigger fires only after the events that fired them are executed successfully. They
cannot be used as INSTEAD OF triggers.

 ALTER TABLE

 CREATE TABLE

 DROP TABLE

Syntax :

CREATE TRIGGER triggername

ON DATABASE

FOR

CREATE_TABLE,

ALTER_TABLE,

DROP_TABLE

AS

BEGIN

SET NOCOUNT ON;

INSERT INTO Tablename();

VAlUE();

END;
BEFORE UPDATE TRIGGER:
BEFORE UPDATE trigger is a type of trigger that is executed automatically before an UPDATE
operation is performed on a table. You can use this trigger to perform certain actions or
validations before the actual update takes place.

Syntax
Syntax to create a BEFORE UPDATE trigger in MySQL:

1. CREATE TRIGGER trigger_name


2. BEFORE UPDATE
3. ON table_name FOR EACH ROW
4. trigger_body ;

BEFORE UPDATE syntax parameters are:

o First, we will specify the trigger name that we want to create. It should be unique within
the schema.
o Second, we will specify the trigger action time, which should be BEFORE UPDATE. This
trigger will be invoked before each row of alterations occurs on the table.
o Third, we will specify the name of a table to which the trigger is associated. It must be
written after the ON keyword. If we did not specify the table name, a trigger would not
exist.
o Finally, we will specify the trigger body that contains a statement for execution when
the trigger is activated.

For executing multiple statements, we will use BEGIN END block that contains a set of queries;

DELIMITER //

CREATE TRIGGER trigger_name

BEFORE UPDATE

ON table_name FOR EACH ROW

BEGIN

variable declarations

trigger code

END;

// DELIMITER ;

Example:
create table op(
q int not null,
asi int not null
);
//inserting values in table;
insert into op
values
(23,90);
insert into op
values
(45,89);
//Declaring local variable
set @message_text=NULL;

//Creating trigger

delimiter //

create trigger updation

before update on op

for each row

begin

if new.q<0 then

set @message_text='cant update';

end if;

if new.q>=0 then

set @message_text='updated';

end if ;

end;

// delimiter ;

//Updating record

update op

set q=0

where q=23;

//Displaying result

select @message_text;

OUTPUT
BEFORE INSERT
BEFORE INSERT trigger is a type of trigger that is executed automatically before an INSERT
operation is performed on a table.

Syntax
Syntax to create a BEFORE INSERT trigger in MySQL:

1. CREATE TRIGGER trigger_name


2. BEFORE INSERT
3. ON table_name FOR EACH ROW
4. Trigger_body ;

BEFORE INSERT trigger syntax parameter:

o First, we will specify the name of the trigger that we want to create. It should be unique
within the schema.
o Second, we will specify the trigger action time, which should be BEFORE INSERT. This
trigger will be invoked before each row modifications occur on the table.
o Third, we will specify the name of a table to which the trigger is associated. It must be
written after the ON keyword. If we did not specify the table name, a trigger would not
exist.
o Finally, we will specify the statement for execution when the trigger is activated.

For executing multiple statements, we will use BEGIN END block that contains a set of queries.

DELIMITER //

CREATE TRIGGER trigger_name

BEFORE INSERT ON table_name

FOR EACH ROW

BEGIN

variable declarations

trigger code

END
// DELIMITER ;

Example
//creating table

create table sumup(

a int not null,

b varchar(50) not null

);

//inserting values in table

insert into sumup

values (90,'rehan');

//Declaring local variable

set @sum=0;

//creating trigger

create trigger uiop.sum

before insert on uiop.cvb

for each row set @sum=@sum+new.a;

//Again inserting values in table

insert into uiop.cvb

values (9,'h');

insert into uiop.cvb

values

(89,'u');

//Displaying result

select @sum;

OUTPUT
HOW TO SHOW TRIGGERS IN DATABASE?
To show triggers currently defined for tables in a database we use different MYSQL commands
FIRST COMMAND
For active database, p with table op
Show triggers;
This command will list all the triggers defined on tables.

Show triggers output has these columns:


 Trigger
The name of the trigger.
 Event
The trigger event. This is the type of operation on the associated table for which the trigger
activates. The value is INSERT (a row was inserted), DELETE (a row was deleted), or UPDATE (a
row was modified).
 Table
The table for which the trigger is defined.
 Statement
The trigger body; that is, the statement executed when the trigger activates.
 Timing
Whether the trigger activates before or after the triggering event. The value
is BEFORE or AFTER.
 Created
The date and time when the trigger was created. This is a TIMESTAMP(2) value (with a
fractional part in hundredths of seconds) for triggers.
 sql_mode
The SQL mode in effect when the trigger was created, and under which the trigger executes.
For the permitted values.
 Definer
The account of the user who created the trigger, in 'user_name'@'host_name' format.
 character_set_client
The session value of the character_set_client system variable when the trigger was created.
 collation_connection
The session value of the collation_connection system variable when the trigger was created.
 Database Collation
The collation of the database with which the trigger is associated.
SECOND COMMAND FOR INACTIVE DATABASE
Use database-name;
Show triggers;

AFTER DELETE TRIGGER:


The AFTER DELETE Trigger in MySQL is invoked automatically whenever a delete event
is fired on the table. In this article, we are going to learn how to create an AFTER DELETE
trigger with its syntax and example.

Syntax
The following is the syntax to create an AFTER DELETE trigger in MySQL:

1. CREATE TRIGGER trigger_name


2. AFTER DELETE
3. ON table_name FOR EACH ROW
4. Trigger_body ;

The AFTER DELETE trigger syntax parameter can be explained as below:

o First, we will specify the name of the trigger that we want to create. It should
be unique within the schema.
o Second, we will specify the trigger action time, which should be AFTER DELETE.
This trigger will be invoked after each row of alterations occurs on the table.
o Third, we will specify the name of a table to which the trigger is associated. It
must be written after the ON keyword. If we did not specify the table name, a
trigger would not exist.
o Finally, we will specify the trigger body that contains a statement for execution
when the trigger is activated.

If we want to execute multiple statements, we will use the BEGIN END block that contains a
set of SQL queries to define the logic for the trigger. See the below syntax:

1. DELIMITER $$
2. CREATE TRIGGER trigger_name AFTER DELETE
3. ON table_name FOR EACH ROW
4. BEGIN
5. variable declarations
6. trigger code
7. END$$
8. DELIMITER ;

EXAMPLE:
CREATE TABLE employees (

employee_id INT PRIMARY KEY,

employee_name VARCHAR(255)

);

CREATE TABLE deleted_employees (

deleted_id INT PRIMARY KEY,

deleted_name VARCHAR(255),

);

DELIMITER //

CREATE TRIGGER after_delete_employee

AFTER DELETE ON employees

FOR EACH ROW

BEGIN

INSERT INTO deleted_employees (deleted_id, deleted_name, )

VALUES (OLD.employee_id, OLD.employee_name, );

END;

//

DELIMITER ;

BEFORE DELETE TRIGGER:


BEFORE DELETE Trigger in MySQL is invoked automatically whenever a delete
operation is fired on the table. In this article, we are going to learn how to create a
before delete trigger with its syntax and example.

Syntax
The following is the syntax to create a BEFORE DELETE trigger in MySQL:

1. CREATE TRIGGER trigger_name


2. BEFORE DELETE

1. ON table_name FOR EACH ROW


2. Trigger_body ;

The BEFORE DELETE trigger syntax parameter can be explained as below:

o First, we will specify the name of the trigger that we want to create. It should be
unique within the schema.
o Second, we will specify the trigger action time, which should be BEFORE DELETE.
This trigger will be invoked before each row of alterations occurs on the table.
o Third, we will specify the name of a table to which the trigger is associated. It
must be written after the ON keyword. If we did not specify the table name, a
trigger would not exist.
o Finally, we will specify the statement for execution when the trigger is activated.

If we want to execute multiple statements, we will use the BEGIN END block that contains a
set of queries to define the logic for the trigger. See the below syntax:

1. DELIMITER $$
2. CREATE TRIGGER trigger_name BEFORE DELETE
3. ON table_name FOR EACH ROW
4. BEGIN
5. variable declarations
6. trigger code
7. END$$
8. DELIMITER ;

EXAMPLE:
-- Create the orders table CREATE TABLE

orders (

order_id INT PRIMARY KEY,order_date DATE


);

-- Create the order_items table CREATE TABLE

order_items (

item_id INT PRIMARY KEY,order_id INT,

item_name VARCHAR(255),quantity INT

);

-- Create the trigger

DELIMITER //

CREATE TRIGGER before_delete_orderBEFORE DELETE ON

orders

FOR EACH ROWBEGIN

-- Delete corresponding order items

DELETE FROM order_items WHERE order_id =OLD.order_id;

END;

// Delimiter ;

Advantages and disadvantages of my sql:


Advantages of SQL Triggers
1) It helps in maintaining the integrity constraints in the database
tables, especially when the primary key and foreign key constrain are not defined.
2) It sometimes also helps in keeping the SQL codes short and simple as I show in the real-
life example.

3) It helps in maintaining the track of all the changes (update, deletion and insertion)occurs in
the tables through inserting the changes values in the audits tables.

4) Sometimes if the code is not well managed, then it can help in maintaining the database
constraints defined on the tables on which the trigger is defined. For example, suppose if
have a situation that there is an online learning system in whicha user can register in the
multiple course.

Disadvantages of Triggers
1) Hard to maintain since this may be a possibility that the new developer doesn’table to
know about the trigger defined in the database and wonder how data is inserted,
deleted or updated automatically.

2) They are hard to debug since they are difficult to view as compared to stored
procedures, views, functions, etc.

3) Excessive or over use of triggers can slow down the performance of the applicationsince if
we defined the triggers in many tables then they kept automatically executing every time
data is inserted, deleted or updated in the tables (based on the trigger’s definition) and it
makes the processing very slow.

4) If complex code is written in the triggers, then it will slow down the performanceof the
applications.

5) The cost of creation of triggers can be more on the tables on which frequency of
DML (insert, delete and update) operation like bulk insert is high.

You might also like