Feed: Planet MySQL
;
Author: Krunal Lathiya
;
SQL Triggers Tutorial With Example | Triggers in SQL is today’s topic. SQL trigger is invoked by the database automatically when any change in the event occurs. It is known as a particular type of stored procedure because triggers are called directly, which is not done in case of stored procedures. The only difference between SQL triggers and stored procedures is that stored procedure needs to be called explicitly, whereas SQL triggers are called implicitly. SQL triggers are invoked when a row is inserted in a table, or any columns are being updated.
Content Overview
SQL Triggers Tutorial With Example
Triggers are the stored programs, which are automatically fired or executed when some events take place. It is like event-based programming. Triggers are written to be executed in the response to any of the following events.
- The database manipulation (DML) statement (DELETE, INSERT, or UPDATE)
- The database definition (DDL) statement (CREATE, ALTER, or DROP).
- The database operation (SERVERERROR, LOGIN, LOGOUT, STARTUP, or SHUTDOWN).
Triggers can be defined on the table, view, schema, or database with which an event is associated.
The trigger is a stored procedure in the database which automatically invokes whenever the special event in a database occurs. For example, the trigger can be invoked when the row is inserted into the specified table or when the certain table columns are being updated.
#Syntax
Create trigger [trigger name] [before/after] {insert/update/delete} On [table_name] [for each row] [trigger_body]
#Parameters
- create trigger [trigger name]: Used for creating or replacing an already created trigger with new trigger name.
- [before | after]: This statement is used for specifying when the trigger will be executed. Before trigger is used to run the triggers before the triggering statement is run. After a trigger is used to run the triggers after the triggering statement is run.
- {insert | update | delete}: This specifies the operation which we want to perform in the tables.
- on [table_name]: This is the name of the table.
- [for each row]: This statement is associated with row triggers, i.e., triggers will be invoked when any row is affected.
- [trigger_body]: It provides the operation to be performed at the time trigger is fired.
Let’s understand by this with an example.
Consider a table: (Students)
Field | Type | NULL | Key | Default | Extra |
Roll No | Int(2) | NO | PRI | NULL | |
Name | Varchar(40) | YES | NULL | ||
English | Int(2) | YES | NULL | ||
Physics | Int(2) | YES | NULL | ||
Chemistry | Int(2) | YES | NULL | ||
Maths | Int(2) | YES | NULL | ||
Total | Int(2) | YES | NULL | ||
Per | Int(2) | YES | NULL |
#Query: (SQL TRIGGER)
create trigger marks before insert on students for each row set new.total=new.english+new.physics+new.chemistry+new.maths, new.per=(new.total/400)*100;
#Explanation to the above query
Name of the trigger is the marks. Now total and percentage will be automatically calculated and stored in the table students as soon as we insert any rows in the table.
Notice, that we have set total using a new keyword because we are not dealing with the old rows instead, we are inserting new rows so after total all other statements are suffixed with new keyword with a dot operator.
Now we are going to insert values.
insert into students values(1,"Shouvik",83,79,80,50,0,0);
#Explanation to the above query
We have inserted the values in the same format as we used to add. We have set the total and percentage values as 0, which will be computed and updated automatically by triggering statements.
#Output
#Advantages of using SQL triggers
- It is used for checking the integrity of the data.
- Triggers can be used for catching errors in any fields.
- SQL triggers are a better alternative for running scheduled tasks, i.e. by using SQL triggers we don’t have to wait for running the tasks planned because the triggers get automatically invoked whenever there is any change in the table.
- SQL triggers are also used for official inspection of data in the tables.
#Disadvantages of using SQL triggers
- SQL triggers are used for providing an extended validation, and they cannot be used for replacing all the validation which can be done only by the application layer.
- SQL triggers are executed from the client applications, which will be challenging to figure out what is happening in the database layer.
- It increases the overhead of the database server.
#Another Example of SQL Trigger
If we want to start with, we will be using the CUSTOMERS table. See the following customers table with its columns and values.
Select * from customers; +----+----------+-----+-----------+----------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+----------+-----+-----------+----------+ | 1 | Ramesh | 32 | Ahmedabad | 2000.00 | | 2 | Khilan | 25 | Delhi | 1500.00 | | 3 | kaushik | 23 | Kota | 2000.00 | | 4 | Chaitali | 25 | Mumbai | 6500.00 | | 5 | Hardik | 27 | Bhopal | 8500.00 | | 6 | Komal | 22 | MP | 4500.00 | +----+----------+-----+-----------+----------+
The following program creates the row-level trigger for the customer’s table that would fire for the INSERT or UPDATE or DELETE operations performed on the CUSTOMERS. The trigger will display the salary difference between old values and new values.
CREATE OR REPLACE TRIGGER display_salary_changes BEFORE DELETE OR INSERT OR UPDATE ON customers FOR EACH ROW WHEN (NEW.ID > 0) DECLARE sal_diff number; BEGIN sal_diff := :NEW.salary - :OLD.salary; dbms_output.put_line('Old salary: ' || :OLD.salary); dbms_output.put_line('New salary: ' || :NEW.salary); dbms_output.put_line('Salary difference: ' || sal_diff); END; /
When the above code is executed at the SQL prompt, it produces the following output.
Trigger created.
The following points need to be considered here.
-
OLD and NEW references are not available for the table-level triggers; instead, you can use them for the record-level triggers.
- If you want to query a table in the same trigger, then you should use a AFTER keyword, because the triggers can query a table or change it again only after an initial change is applied and the table is back in the consistent state.
-
The above trigger has been written in such a way that it will fire before any DELETE or INSERT or UPDATE operation on a table, but you can write your trigger on the single or multiple operations. For example BEFORE DELETE, which will fire whenever a record will be deleted using the DELETE operation on the table.
#Triggering the Trigger
Let us execute some Data Manipulation operations on the CUSTOMERS table. Here is one INSERT statement, which will a create the new record in the database table.
INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY) VALUES (7, 'Kriti', 22, 'HP', 7500.00 );
When the record is created in the CUSTOMERS table, the above create the trigger, display_salary_changes will be fired, and it will display the following output.
Old salary: New salary: 7500 Salary difference:
Because this is a new record, the old salary is not available, and the above result comes as null. Let us execute one more DML operation on the CUSTOMERS table. The UPDATE statement will modify the existing record in the table.
UPDATE customers SET salary = salary + 500 WHERE id = 2;
When the record is updated in the CUSTOMERS table, the above create a trigger, the display_salary_changes will be fired, and it will show the following result.
Old salary: 1500 New salary: 2000 Salary difference: 500
Finally, SQL Triggers Tutorial With Example | Triggers in SQL is over.