Professional Documents
Culture Documents
TRiggers
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.
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
BEGIN
--variable declarations
--trigger code
END;
Example
CREATE TABLE student (
name VARCHAR(255),
marks INT,
percentage DECIMAL(5,2)
);
DELIMITER //
//
DELIMITER ;
TYPES OF TRIGGER ;
There are three type of trigger in SQL server but in MYSQL there are only two types that are given
below:
LOGON
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.
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.
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.
ON table_name
AS
BEGIN
-- Trigger 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.
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.
ON table_name
AS
BEGIN
-- trigger statements
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.
Before insert
Before update
Before delete
Syntax:
AS
BEGIN
-- Trigger 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 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 :
ON DATABASE
FOR
CREATE_TABLE,
ALTER_TABLE,
DROP_TABLE
AS
BEGIN
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:
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 //
BEFORE UPDATE
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 //
before update on op
begin
if new.q<0 then
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:
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 //
BEGIN
variable declarations
trigger code
END
// DELIMITER ;
Example
//creating table
);
values (90,'rehan');
set @sum=0;
//creating trigger
values (9,'h');
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.
Syntax
The following is the syntax to create an AFTER DELETE trigger in MySQL:
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_name VARCHAR(255)
);
deleted_name VARCHAR(255),
);
DELIMITER //
BEGIN
END;
//
DELIMITER ;
Syntax
The following is the syntax to create a BEFORE DELETE trigger in MySQL:
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_items (
);
DELIMITER //
orders
END;
// Delimiter ;
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.