How To Write SQL Triggers
How To Write SQL Triggers
SERIES
How TO Create
SQL Triggers
Triggers are useful for automating repetitive tasks. You can just set
up a trigger to do some calculation after every specific database
action.
In this post, you'll learn how to create triggers, how to drop them,
and when they're useful.
How to Create A Trigger
To create a new trigger, use the CREATE TRIGGER command. This
command has the following structure:
linkedin.com/in/ileonjose
The trigger_event is another variable that has a limited number of
possible options. This variable cannot be any value other than
INSERT, UPDATE, or DELETE. It specifies what event to listen for.
table_name is the name of the table the trigger should watch. This
has to be the name of an existing table in your database, but it
can be an empty table.
The FOR EACH ROW is the other mandatory part of the trigger
definition.
trigger_body is the SQL query that you want to be run when this
trigger is fired.
CREATE TABLE
users (
fullname VARCHAR(120),
email VARCHAR(120),
username VARCHAR(30),
password VARCHAR(60));
linkedin.com/in/ileonjose
Now, we can create a simple trigger and attach it to this empty table.
A trigger that encrypts string passwords before they are inserted
using the MD5 function would make sense.
You can only modify these values if your set event_time is BEFORE. If
the event_time is set to AFTER, the data has already been stored
before getting to the trigger so it cannot be modified again.
You can use the NEW keyword in INSERT and UPDATE events but not
the DELETE event.
linkedin.com/in/ileonjose
There's also the OLD keyword that you can use in DELETE and
UPDATE event triggers that gives you access to the former values of
the affected record. You can't use this keyword on an INSERT event
because there is no previous record before new data is created.
INSERT INTO
users
VALUES
(
'idris babu',
'[email protected]',
'zubby1',
'password'
);
Check your table for the values. You should have something like this:
linkedin.com/in/ileonjose
How to Drop a Trigger
After creating a trigger, you might want to stop its execution for
some reason. In this case, you can drop the trigger.
To drop the trigger, use the DROP TRIGGER command. The command
only requires the name of the trigger. You can use the command like
this:
Running this query will remove the trigger that we created above and
every record inserted from now on will not have the password
encrypted.
To test this, insert the same record as before, and check the result.
linkedin.com/in/ileonjose
When to Use Triggers
Logging: You can have a trigger to automatically write to another
table on insertion, update, or deletion of record from a table.
I hope you now understand SQL triggers and when to use them so
you can write better queries.
linkedin.com/in/ileonjose
HELPFUL? REPOST
linkedin.com/in/ileonjose