SlideShare a Scribd company logo
S e m i n a r o n D a t a b a s e A u t o m a t i o n
w i t h
M y S Q L T r i g g e r s
a n d
E v e n t S c h e d u l e r s
A b d u l R a h m a n S h e r z a d
L e c t u r e r a t C o m p u t e r S c i e n c e f a c u l t y o f H e r a t U n i v e r s i t y , A f g h a n i s t a n
P h D S t u d e n t a t T U - B e r l i n , G e r m a n y
J a n u a r y 2 7 , 2 0 1 5
MySQL Triggers and Events
• MySQL Triggers are operations that are automatically performed when a
specified database event (INSERT, UPDATE, DELETE) occurs.
• Ideally, triggers should be considered when they automate changes which are
specific to the database or management of its data.
– Data integrity, logging and auditing, business logic, perform calculations, run
further SQL commands, etc.
• MySQL Events can be scheduled to run once or more during specific periods.
Effectively, they are database-only cron-jobs and can be used in many cases
such as:
– optimizing database tables, archiving data, cleaning up logs, or generate complex
reports during off-peak time.
2
More about
MySQL Triggers
3
Introduction to MySQL Triggers
• A trigger is a set of SQL statements that is invoked or fired automatically when a
change is made to the data on the associated table either before or after the data
is changed by DML statements (INSERT, UPDATE or DELETE).
• MySQL version 5.7.2 allows you to define maximum six triggers for each table.
– BEFORE INSERT
– AFTER INSERT
– BEFORE UPDATE
– AFTER UPDATE
– BEFORE DELETE
– AFTER DELETE
MySQL 5.7.2+ removes this limitation and allows creation of multiple triggers for
the same event and action time in a table.
4
Introduction to MySQL Triggers II
• The trigger is not invoked with statement that makes change to the table but does
not use INSERT, DELETE or UPDATE statement.
– For example, the TRUNCATE statement removes the whole data of a table but does not
invoke the trigger associated with that table.
• The triggers are invoked with statements that use the INSERT statement behind
the scenes.
– For example, REPLACE statement and LOAD DATA statement.
• Database triggers are special types of stored procedures.
– Special because they are not called explicitly like stored procedures.
• Triggers are supported in MySQL, PostgreSQL, SQLite, Firebird, DB2, Microsoft
SQL Server and Oracle.
– Implementation varies, therefore, the appropriate documentation before coding should
be checked.
5
MySQL Triggers
Advantages
• SQL triggers provide an alternative
way to check the integrity of data.
• SQL triggers provide an alternative
way to run scheduled tasks.
– By using SQL triggers, no need to
wait to run the scheduled tasks
because the triggers are
invoked automatically before or
after a change is made to the data in
tables.
• SQL triggers are very useful to log
and audit the changes of data in
tables.
Disadvantages
• SQL triggers only can provide an extended
validation and they cannot replace all the
validations. Some simple validations have to be
done in the application layer. For example, user's
inputs can be validated on the client side or server
side.
• SQL triggers are invoked and executed invisibly
from client-applications therefore it is difficult to
figure out what happen in the database layer.
• SQL triggers may increase the overhead of the
database server.
6
Caution!!!
• Triggers should not be used in place of foreign key constraints.
• Triggers are not a substitute for transactions.
• Avoid duplication of effort.
– The back-end code should be sanitizing user input so it should not be necessary
to repeat those checks within the database.
• Triggers will execute quicker than a series of SQL commands passed by
back-end code
– but using complex triggers on regularly modified tables should be avoided.
7
MySQL Trigger Limitation
• MySQL triggers cover all features defined in the standard SQL. However,
triggers cannot use:
– SHOW, LOAD DATA, LOAD TABLE, BACKUP DATABASE, RESTORE, FLUSH and
RETURN statements.
– Statements that commit or rollback implicitly or explicitly such as COMMIT,
ROLLBACK, START TRANSACTION, LOCK / UNLOCK TABLES, ALTER, CREATE, DROP,
RENAME, etc.
– Prepared statements such as PREPARE, EXECUTE, etc.
– Dynamic SQL statements.
MySQL version 5.1.4+ a trigger can call a stored procedure or stored function, which
was a limitation is the previous versions.
8
MySQL Trigger Storage and Backup
• MySQL stores triggers in a data directory e.g.
/data/database_name/ with the files named table_name.TRG
and trigger_name.TRN
– The table_name.TRG file maps the trigger to the corresponding table.
– the trigger_name.TRN file contains the trigger definition.
• To back up the MySQL triggers
– Copy the trigger files to the backup directory.
– Use the mysqldump tool.
9
Create MySQL Trigger Basic Syntax
10
CREATE TRIGGER trigger_name trigger_time trigger_event
ON table_name
FOR EACH ROW
BEGIN
-- the trigger body
-- this code is applied to every
-- inserted/updated/deleted row
END;
Create MySQL Trigger Syntax Details
• The trigger name comes after the CREATE TRIGGER statement.
– The trigger name should follow the naming convention [table name]_[trigger
time]_ [trigger event].
• Trigger activation time can be BEFORE or AFTER.
• The trigger event can be INSERT, UPDATE or DELETE.
• The table name must specify after the ON keyword.
– A trigger must be associated with a specific table. Without a table trigger would not
exist.
• The trigger body is a set of SQL commands to run and are placed between
BEGIN and END block. This is where the logic for the trigger is defined.
11
Notice!
• In the trigger defined for INSERT
– NEW keyword can be used only.
– OLD keyword can not be used.
• In the trigger defined for DELETE
– there is no new row. Therefore, the OLD keyword can be used only.
• In the UPDATE trigger
– OLD keyword refers to the row before it is updated.
– NEW keyword refers to the row after it is updated.
12
MySQL Trigger
Application
Scenario
13
MySQL Trigger Application Scenario
• A small example database with two tables as follow:
– Blog: stores a unique ID, the title, content, and a deleted flag.
– Audit: stores a basic set of historical changes with an ID, the blog ID, the old blog
title, the change type (NEW, EDIT or DELETE), and the date/time of that change.
• INSERT into the blog table
– A new entry into the audit table containing the blog ID, the title, and a type of 'NEW'
(or 'DELETE' if it was deleted immediately) should be added.
• UPDATE in the blog table
– A new entry into the audit table containing the blog ID, the title, and a type of 'EDIT'
(or 'DELETE' if the deleted flag is set) should be added.
The 'changetime' attribute will automatically be set to the current time.
14
Database Schema
15
Blog Schema
CREATE TABLE blog (
id INT NOT NULL AUTO_INCREMENT,
title VARCHAR(255),
content text,
deleted TINYINT(1) unsigned NOT NULL DEFAULT '0',
PRIMARY KEY (id),
KEY (deleted)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
16
Audit Schema
CREATE TABLE audit (
id INT PRIMARY KEY NOT NULL AUTO_INCREMENT,
blog_id INT NOT NULL,
blog_title VARCHAR(255) NOT NULL,
changetype ENUM('NEW','EDIT','DELETE') NOT NULL,
changetime timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
KEY (blog_id),
CONSTRAINT FOREIGN KEY (blog_id) REFERENCES blog (id)
ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
17
Notice: Delimiter
• Most of the time the trigger body requires a number of SQL
commands separated by a semi-colon (;).
• To create the full trigger code the delimiter must be changed
to something else. For example
– $$
– //
• Finally, after trigger code completion the delimiter back should
be set to a semi-colon.
18
Trigger: AFTER INSERT
DELIMITER $$
CREATE TRIGGER blog_after_insert AFTER INSERT
ON blog
FOR EACH ROW
BEGIN
IF NEW.deleted THEN
SET @changetype = 'DELETE';
ELSE
SET @changetype = 'NEW';
END IF;
INSERT INTO audit (blog_id, blog_title, changetype) VALUES (NEW.id, NEW.title, @changetype);
END; $$
DELIMITER ;
19
Trigger: AFTER UPDATE
DELIMITER $$
CREATE TRIGGER blog_after_update AFTER UPDATE
ON blog
FOR EACH ROW
BEGIN
IF NEW.deleted THEN
SET @changetype = 'DELETE';
ELSE
SET @changetype = 'EDIT';
END IF;
INSERT INTO audit (blog_id, blog_title, changetype) VALUES (NEW.id, OLD.title, @changetype);
END; $$
DELIMITER ;
20
Test the Triggers
• Let's see what happens when we insert a new post into our blog table:
INSERT INTO blog (title, content) VALUES ('First blog', 'The first blog content');
SELECT * FROM blog;
SELECT * FROM audit;
• Let's update our blog text:
UPDATE blog SET title = 'First blog Edited' WHERE id = 1;
SELECT * FROM audit;
• Finally, let's mark the post as deleted:
UPDATE blog SET deleted = 1 WHERE id = 1;
SELECT * FROM audit;
21
More about
MySQL Events
22
Introduction to MySQL Events
• MySQL events were added in MySQL 5.1.6 and offer an alternative to
scheduled tasks and cron jobs.
• Events can be used to create backups, delete out-of-date and old records,
aggregate data for reports, etc.
• Unlike standard triggers which execute given a certain condition, an event
is an object that is triggered by the passage of time and is sometimes
referred to as a 'temporal trigger'.
• MySQL events can be scheduled to run either once or at a recurring interval
– when the server traffic will be low.
23
Starting the Event Scheduler
• The MySQL event scheduler is a process that runs in the
background and constantly looks for events to execute.
• Before creating or scheduling an event, first the scheduler
needs to turn on, with issuing the following command:
SET GLOBAL event_scheduler = ON;
• With the following the scheduler status is revealed if it is ON or
OFF:
SHOW PROCESSLIST;
24
Create MySQL Event Basic Syntax
CREATE EVENT event_name
ON SCHEDULE the_schedule
[ON COMPLETION [NOT] PRESERVE]
[ENABLE | DISABLE | DISABLE ON SLAVE]
DO BEGIN
-- the event body
END;
25
The Schedule Settings
• Run once on a specific date/time:
– AT 'YYYY-MM-DD HH:MM.SS'
• AT '2016-01-15 02:00.00'
• Run once after a specific period has elapsed:
– AT CURRENT_TIMESTAMP + INTERVAL n [HOUR|MONTH|WEEK|DAY|MINUTE]
• AT CURRENT_TIMESTAMP + INTERVAL 1 DAY
• Run at specific intervals forever:
– EVERY n [HOUR|MONTH|WEEK|DAY|MINUTE]
• EVERY 1 DAY
• Run at specific intervals during a specific period:
– EVERY n [HOUR|MONTH|WEEK|DAY|MINUTE] STARTS date ENDS date
• EVERY 1 DAY STARTS CURRENT_TIMESTAMP + INTERVAL 1 WEEK ENDS '2017-01-01 00:00.00'
26
Caution!!!
• An event is normally dropped once its schedule has expired
– ON COMPLETION NOT PRESERVE
• To prevent that behavior set
– ON COMPLETION PRESERVE
27
Run Once Event Example
DELIMITER $$
CREATE EVENT one_time_event_example
ON SCHEDULE AT CURRENT_TIMESTAMP + INTERVAL 5 MINUTE
DO BEGIN
UPDATE blog SET title = "One time event example" WHERE id = 1;
END; $$
DELIMITER ;
• This event will run once, one hour from the time it was created.
28
Preserved Event Example
DELIMITER $$
CREATE EVENT preserved_event_example
ON SCHEDULE AT CURRENT_TIMESTAMP + INTERVAL 1 HOUR
ON COMPLETION PRESERVE
DO BEGIN
UPDATE blog SET title = "Preserve event example" WHERE id = 1;
END; $$
DELIMITER ;
• To specify a preserved event, the ON COMPLETION PRESERVE clause
must be used.
29
Reoccurring Event Example
DELIMITER $$
CREATE EVENT reoccurring_event_example
ON SCHEDULE EVERY 1 HOUR
DO BEGIN
UPDATE blog SET title = "Reoccurring event example" WHERE id = 1;
END; $$
DELIMITER ;
• To specify a recurring event, the EVERY clause must be used.
• In this example, the reoccurring event would start tomorrow and continue
to run every hour for a full year.
30
MySQL Event
Application
Scenario
31
MySQL Event Application Scenario
• The database example used for trigger application has a problem.
– The old blog posts are marked as deleted rather than being removed from the blog
table.
– The blog table will grow indefinitely and become slower over time.
– The old blog posts could be purged, but that would remove them forever.
• As a result, we will move the blog posts and their associated audit records to
archive tables.
– The archive tables can grow without affecting the speed of the main web application and
we can undelete the old blog posts if necessary.
• Two archive tables are required:
– blog_archive: identical to the blog table except it does not require a deleted flag or an
auto-incrementing ID.
– audit_archive: identical to the audit table except the timestamp is not automatically
generated and it does not require an auto-incrementing ID.
32
MySQL Event Application Scenario II
• A scheduled event is required to:
– Copies blog posts from blog to blog_archive when the deleted flag is set
to 1.
– Copies the associated audit entries for those blog posts from audit to
audit_archive.
– Physically deletes the archived blog posts from the blog table.
– Referential integrity has been defined with a foreign key. Therefore, all
the associated audit entries for those blog posts will also be removed.
33
Database Schema
34
Blog Archive Schema
CREATE TABLE blog_archive (
id INT NOT NULL,
title VARCHAR(255),
content text,
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
35
Audit Archive Schema
CREATE TABLE audit_archive (
id INT PRIMARY KEY NOT NULL,
blog_id INT NOT NULL,
blog_title VARCHAR(255),
changetype ENUM('NEW','EDIT','DELETE') NOT NULL,
changetime timestamp NOT NULL,
KEY (blog_id),
CONSTRAINT FOREIGN KEY (blog_id) REFERENCES blog_archive (id)
ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
36
The Archive Event
DELIMITER $$
CREATE EVENT archive_blog_posts
ON SCHEDULE EVERY 1 WEEK STARTS '2016-01-22 01:00:00'
DO BEGIN
-- copy deleted posts
INSERT INTO blog_archive (id, title, content) SELECT id, title, content FROM blog
WHERE deleted = 1;
-- copy associated audit records
INSERT INTO audit_archive (id, blog_id, blog_title, changetype, changetime)
SELECT audit.id, audit.blog_id, audit.blog_title, audit.changetype, audit.changetime
FROM audit JOIN blog ON audit.blog_id = blog.id WHERE blog.deleted = 1;
-- remove deleted blogs and audit entries
DELETE FROM blog WHERE deleted = 1;
END; $$
DELIMITER ;
• In the example, the event runs every week on Friday morning.
37
Wrap up
• The Triggers are powerful tools for protecting the integrity of
the data in the databases
– Data integrity, logging and auditing, business logic, perform
calculations, run further SQL commands, etc.
• The Events are very useful to automate some database
operations
– optimizing database tables, cleaning up logs, archiving data, or
generate complex reports during off-peak time.
38
Abdul Rahman
Sherzad
• Thank you for your participation
– Herat University
– Hariwa Institute of Higher Education
– Ghalib University
– Khaja Abdullah Ansari Institute of
Higher Education
– ICT Companies
Lecturer at Computer Science
faculty of Herat University,
Afghanistan.
PhD Student at Technical
University of Berlin (TU-Berlin),
Germany.
January 27, 2015
39
40
41
42
Ad

More Related Content

What's hot (20)

Stored procedure in sql server
Stored procedure in sql serverStored procedure in sql server
Stored procedure in sql server
baabtra.com - No. 1 supplier of quality freshers
 
SQL subquery
SQL subquerySQL subquery
SQL subquery
Vikas Gupta
 
Database Triggers
Database TriggersDatabase Triggers
Database Triggers
Aliya Saldanha
 
MySQL: Indexing for Better Performance
MySQL: Indexing for Better PerformanceMySQL: Indexing for Better Performance
MySQL: Indexing for Better Performance
jkeriaki
 
Transformations and actions a visual guide training
Transformations and actions a visual guide trainingTransformations and actions a visual guide training
Transformations and actions a visual guide training
Spark Summit
 
Elk stack
Elk stackElk stack
Elk stack
Jilles van Gurp
 
Difference Between Sql - MySql and Oracle
Difference Between Sql - MySql and OracleDifference Between Sql - MySql and Oracle
Difference Between Sql - MySql and Oracle
Steve Johnson
 
Stored procedures
Stored proceduresStored procedures
Stored procedures
Prof.Nilesh Magar
 
MongoDB WiredTiger Internals: Journey To Transactions
MongoDB WiredTiger Internals: Journey To TransactionsMongoDB WiredTiger Internals: Journey To Transactions
MongoDB WiredTiger Internals: Journey To Transactions
Mydbops
 
PostgreSQL WAL for DBAs
PostgreSQL WAL for DBAs PostgreSQL WAL for DBAs
PostgreSQL WAL for DBAs
PGConf APAC
 
Trigger
TriggerTrigger
Trigger
Slideshare
 
SQLite - Overview
SQLite - OverviewSQLite - Overview
SQLite - Overview
Emanuele Bartolesi
 
Introduction to PgBench
Introduction to PgBenchIntroduction to PgBench
Introduction to PgBench
Joshua Drake
 
Oracle Database View
Oracle Database ViewOracle Database View
Oracle Database View
Eryk Budi Pratama
 
Stored-Procedures-Presentation
Stored-Procedures-PresentationStored-Procedures-Presentation
Stored-Procedures-Presentation
Chuck Walker
 
Packages in PL/SQL
Packages in PL/SQLPackages in PL/SQL
Packages in PL/SQL
Pooja Dixit
 
Procedures and triggers in SQL
Procedures and triggers in SQLProcedures and triggers in SQL
Procedures and triggers in SQL
Vikash Sharma
 
MYSQL
MYSQLMYSQL
MYSQL
Ankush Jain
 
Redo log improvements MYSQL 8.0
Redo log improvements MYSQL 8.0Redo log improvements MYSQL 8.0
Redo log improvements MYSQL 8.0
Mydbops
 
Advanced SQL
Advanced SQLAdvanced SQL
Advanced SQL
Sabiha M
 
MySQL: Indexing for Better Performance
MySQL: Indexing for Better PerformanceMySQL: Indexing for Better Performance
MySQL: Indexing for Better Performance
jkeriaki
 
Transformations and actions a visual guide training
Transformations and actions a visual guide trainingTransformations and actions a visual guide training
Transformations and actions a visual guide training
Spark Summit
 
Difference Between Sql - MySql and Oracle
Difference Between Sql - MySql and OracleDifference Between Sql - MySql and Oracle
Difference Between Sql - MySql and Oracle
Steve Johnson
 
MongoDB WiredTiger Internals: Journey To Transactions
MongoDB WiredTiger Internals: Journey To TransactionsMongoDB WiredTiger Internals: Journey To Transactions
MongoDB WiredTiger Internals: Journey To Transactions
Mydbops
 
PostgreSQL WAL for DBAs
PostgreSQL WAL for DBAs PostgreSQL WAL for DBAs
PostgreSQL WAL for DBAs
PGConf APAC
 
Introduction to PgBench
Introduction to PgBenchIntroduction to PgBench
Introduction to PgBench
Joshua Drake
 
Stored-Procedures-Presentation
Stored-Procedures-PresentationStored-Procedures-Presentation
Stored-Procedures-Presentation
Chuck Walker
 
Packages in PL/SQL
Packages in PL/SQLPackages in PL/SQL
Packages in PL/SQL
Pooja Dixit
 
Procedures and triggers in SQL
Procedures and triggers in SQLProcedures and triggers in SQL
Procedures and triggers in SQL
Vikash Sharma
 
Redo log improvements MYSQL 8.0
Redo log improvements MYSQL 8.0Redo log improvements MYSQL 8.0
Redo log improvements MYSQL 8.0
Mydbops
 
Advanced SQL
Advanced SQLAdvanced SQL
Advanced SQL
Sabiha M
 

Similar to Database Automation with MySQL Triggers and Event Schedulers (20)

MySql Triggers Tutorial - The Webs Academy
MySql Triggers Tutorial - The Webs AcademyMySql Triggers Tutorial - The Webs Academy
MySql Triggers Tutorial - The Webs Academy
thewebsacademy
 
Getting Started with MySQL II
Getting Started with MySQL IIGetting Started with MySQL II
Getting Started with MySQL II
Sankhya_Analytics
 
triggers.pptx
triggers.pptxtriggers.pptx
triggers.pptx
Zaid227349
 
11 - Trigger mysql advance materi for student.pptx
11 - Trigger mysql advance materi for student.pptx11 - Trigger mysql advance materi for student.pptx
11 - Trigger mysql advance materi for student.pptx
waonehenry
 
Triggers.PPTX
Triggers.PPTXTriggers.PPTX
Triggers.PPTX
ansariparveen06
 
PostgreSQL Performance Tables Partitioning vs. Aggregated Data Tables
PostgreSQL Performance Tables Partitioning vs. Aggregated Data TablesPostgreSQL Performance Tables Partitioning vs. Aggregated Data Tables
PostgreSQL Performance Tables Partitioning vs. Aggregated Data Tables
Sperasoft
 
[Www.pkbulk.blogspot.com]dbms11
[Www.pkbulk.blogspot.com]dbms11[Www.pkbulk.blogspot.com]dbms11
[Www.pkbulk.blogspot.com]dbms11
AnusAhmad
 
DBA Commands and Concepts That Every Developer Should Know - Part 2
DBA Commands and Concepts That Every Developer Should Know - Part 2DBA Commands and Concepts That Every Developer Should Know - Part 2
DBA Commands and Concepts That Every Developer Should Know - Part 2
Alex Zaballa
 
DBA Commands and Concepts That Every Developer Should Know - Part 2
DBA Commands and Concepts That Every Developer Should Know - Part 2DBA Commands and Concepts That Every Developer Should Know - Part 2
DBA Commands and Concepts That Every Developer Should Know - Part 2
Alex Zaballa
 
Unit 4
Unit 4Unit 4
Unit 4
Abha Damani
 
Triggers
TriggersTriggers
Triggers
Pooja Dixit
 
PLSQL.pptxokokokoo9oooodjdjfjfjfjrjejrjrrjrj
PLSQL.pptxokokokoo9oooodjdjfjfjfjrjejrjrrjrjPLSQL.pptxokokokoo9oooodjdjfjfjfjrjejrjrrjrj
PLSQL.pptxokokokoo9oooodjdjfjfjfjrjejrjrrjrj
KathanPatel49
 
T-SQL & Triggers
T-SQL & TriggersT-SQL & Triggers
T-SQL & Triggers
Ayesha Maqsood
 
NoCOUG_201411_Patel_Managing_a_Large_OLTP_Database
NoCOUG_201411_Patel_Managing_a_Large_OLTP_DatabaseNoCOUG_201411_Patel_Managing_a_Large_OLTP_Database
NoCOUG_201411_Patel_Managing_a_Large_OLTP_Database
Paresh Patel
 
Advanced Topics on Database - Unit-3 AU17
Advanced Topics on Database - Unit-3 AU17Advanced Topics on Database - Unit-3 AU17
Advanced Topics on Database - Unit-3 AU17
LOGANATHANK24
 
Multimedia Databases Concepts: Managing images, video, audio and beyond
Multimedia Databases Concepts: Managing images, video, audio and beyondMultimedia Databases Concepts: Managing images, video, audio and beyond
Multimedia Databases Concepts: Managing images, video, audio and beyond
COSMOS58
 
IR SQLite Session #3
IR SQLite Session #3IR SQLite Session #3
IR SQLite Session #3
InfoRepos Technologies
 
4 trigger
4  trigger4  trigger
4 trigger
Trần Thanh
 
SQL Tunning
SQL TunningSQL Tunning
SQL Tunning
Dhananjay Goel
 
Introduction to triggers
Introduction to triggersIntroduction to triggers
Introduction to triggers
Syed Awais Mazhar Bukhari
 
MySql Triggers Tutorial - The Webs Academy
MySql Triggers Tutorial - The Webs AcademyMySql Triggers Tutorial - The Webs Academy
MySql Triggers Tutorial - The Webs Academy
thewebsacademy
 
Getting Started with MySQL II
Getting Started with MySQL IIGetting Started with MySQL II
Getting Started with MySQL II
Sankhya_Analytics
 
11 - Trigger mysql advance materi for student.pptx
11 - Trigger mysql advance materi for student.pptx11 - Trigger mysql advance materi for student.pptx
11 - Trigger mysql advance materi for student.pptx
waonehenry
 
PostgreSQL Performance Tables Partitioning vs. Aggregated Data Tables
PostgreSQL Performance Tables Partitioning vs. Aggregated Data TablesPostgreSQL Performance Tables Partitioning vs. Aggregated Data Tables
PostgreSQL Performance Tables Partitioning vs. Aggregated Data Tables
Sperasoft
 
[Www.pkbulk.blogspot.com]dbms11
[Www.pkbulk.blogspot.com]dbms11[Www.pkbulk.blogspot.com]dbms11
[Www.pkbulk.blogspot.com]dbms11
AnusAhmad
 
DBA Commands and Concepts That Every Developer Should Know - Part 2
DBA Commands and Concepts That Every Developer Should Know - Part 2DBA Commands and Concepts That Every Developer Should Know - Part 2
DBA Commands and Concepts That Every Developer Should Know - Part 2
Alex Zaballa
 
DBA Commands and Concepts That Every Developer Should Know - Part 2
DBA Commands and Concepts That Every Developer Should Know - Part 2DBA Commands and Concepts That Every Developer Should Know - Part 2
DBA Commands and Concepts That Every Developer Should Know - Part 2
Alex Zaballa
 
PLSQL.pptxokokokoo9oooodjdjfjfjfjrjejrjrrjrj
PLSQL.pptxokokokoo9oooodjdjfjfjfjrjejrjrrjrjPLSQL.pptxokokokoo9oooodjdjfjfjfjrjejrjrrjrj
PLSQL.pptxokokokoo9oooodjdjfjfjfjrjejrjrrjrj
KathanPatel49
 
NoCOUG_201411_Patel_Managing_a_Large_OLTP_Database
NoCOUG_201411_Patel_Managing_a_Large_OLTP_DatabaseNoCOUG_201411_Patel_Managing_a_Large_OLTP_Database
NoCOUG_201411_Patel_Managing_a_Large_OLTP_Database
Paresh Patel
 
Advanced Topics on Database - Unit-3 AU17
Advanced Topics on Database - Unit-3 AU17Advanced Topics on Database - Unit-3 AU17
Advanced Topics on Database - Unit-3 AU17
LOGANATHANK24
 
Multimedia Databases Concepts: Managing images, video, audio and beyond
Multimedia Databases Concepts: Managing images, video, audio and beyondMultimedia Databases Concepts: Managing images, video, audio and beyond
Multimedia Databases Concepts: Managing images, video, audio and beyond
COSMOS58
 
Ad

More from Abdul Rahman Sherzad (20)

Data is the Fuel of Organizations: Opportunities and Challenges in Afghanistan
Data is the Fuel of Organizations: Opportunities and Challenges in AfghanistanData is the Fuel of Organizations: Opportunities and Challenges in Afghanistan
Data is the Fuel of Organizations: Opportunities and Challenges in Afghanistan
Abdul Rahman Sherzad
 
PHP Unicode Input Validation Snippets
PHP Unicode Input Validation SnippetsPHP Unicode Input Validation Snippets
PHP Unicode Input Validation Snippets
Abdul Rahman Sherzad
 
Iterations and Recursions
Iterations and RecursionsIterations and Recursions
Iterations and Recursions
Abdul Rahman Sherzad
 
Sorting Alpha Numeric Data in MySQL
Sorting Alpha Numeric Data in MySQLSorting Alpha Numeric Data in MySQL
Sorting Alpha Numeric Data in MySQL
Abdul Rahman Sherzad
 
PHP Variable variables Examples
PHP Variable variables ExamplesPHP Variable variables Examples
PHP Variable variables Examples
Abdul Rahman Sherzad
 
Cross Join Example and Applications
Cross Join Example and ApplicationsCross Join Example and Applications
Cross Join Example and Applications
Abdul Rahman Sherzad
 
Applicability of Educational Data Mining in Afghanistan: Opportunities and Ch...
Applicability of Educational Data Mining in Afghanistan: Opportunities and Ch...Applicability of Educational Data Mining in Afghanistan: Opportunities and Ch...
Applicability of Educational Data Mining in Afghanistan: Opportunities and Ch...
Abdul Rahman Sherzad
 
Web Application Security and Awareness
Web Application Security and AwarenessWeb Application Security and Awareness
Web Application Security and Awareness
Abdul Rahman Sherzad
 
Mobile Score Notification System
Mobile Score Notification SystemMobile Score Notification System
Mobile Score Notification System
Abdul Rahman Sherzad
 
Herat Innovation Lab 2015
Herat Innovation Lab 2015Herat Innovation Lab 2015
Herat Innovation Lab 2015
Abdul Rahman Sherzad
 
Evaluation of Existing Web Structure of Afghan Universities
Evaluation of Existing Web Structure of Afghan UniversitiesEvaluation of Existing Web Structure of Afghan Universities
Evaluation of Existing Web Structure of Afghan Universities
Abdul Rahman Sherzad
 
PHP Basic and Fundamental Questions and Answers with Detail Explanation
PHP Basic and Fundamental Questions and Answers with Detail ExplanationPHP Basic and Fundamental Questions and Answers with Detail Explanation
PHP Basic and Fundamental Questions and Answers with Detail Explanation
Abdul Rahman Sherzad
 
Java Applet and Graphics
Java Applet and GraphicsJava Applet and Graphics
Java Applet and Graphics
Abdul Rahman Sherzad
 
Fundamentals of Database Systems Questions and Answers
Fundamentals of Database Systems Questions and AnswersFundamentals of Database Systems Questions and Answers
Fundamentals of Database Systems Questions and Answers
Abdul Rahman Sherzad
 
Everything about Database JOINS and Relationships
Everything about Database JOINS and RelationshipsEverything about Database JOINS and Relationships
Everything about Database JOINS and Relationships
Abdul Rahman Sherzad
 
Create Splash Screen with Java Step by Step
Create Splash Screen with Java Step by StepCreate Splash Screen with Java Step by Step
Create Splash Screen with Java Step by Step
Abdul Rahman Sherzad
 
Fal-e-Hafez (Omens of Hafez) Cards in Persian using Java
Fal-e-Hafez (Omens of Hafez) Cards in Persian using JavaFal-e-Hafez (Omens of Hafez) Cards in Persian using Java
Fal-e-Hafez (Omens of Hafez) Cards in Persian using Java
Abdul Rahman Sherzad
 
Web Design and Development Life Cycle and Technologies
Web Design and Development Life Cycle and TechnologiesWeb Design and Development Life Cycle and Technologies
Web Design and Development Life Cycle and Technologies
Abdul Rahman Sherzad
 
Java Virtual Keyboard Using Robot, Toolkit and JToggleButton Classes
Java Virtual Keyboard Using Robot, Toolkit and JToggleButton ClassesJava Virtual Keyboard Using Robot, Toolkit and JToggleButton Classes
Java Virtual Keyboard Using Robot, Toolkit and JToggleButton Classes
Abdul Rahman Sherzad
 
Java Unicode with Live GUI Examples
Java Unicode with Live GUI ExamplesJava Unicode with Live GUI Examples
Java Unicode with Live GUI Examples
Abdul Rahman Sherzad
 
Data is the Fuel of Organizations: Opportunities and Challenges in Afghanistan
Data is the Fuel of Organizations: Opportunities and Challenges in AfghanistanData is the Fuel of Organizations: Opportunities and Challenges in Afghanistan
Data is the Fuel of Organizations: Opportunities and Challenges in Afghanistan
Abdul Rahman Sherzad
 
PHP Unicode Input Validation Snippets
PHP Unicode Input Validation SnippetsPHP Unicode Input Validation Snippets
PHP Unicode Input Validation Snippets
Abdul Rahman Sherzad
 
Sorting Alpha Numeric Data in MySQL
Sorting Alpha Numeric Data in MySQLSorting Alpha Numeric Data in MySQL
Sorting Alpha Numeric Data in MySQL
Abdul Rahman Sherzad
 
Cross Join Example and Applications
Cross Join Example and ApplicationsCross Join Example and Applications
Cross Join Example and Applications
Abdul Rahman Sherzad
 
Applicability of Educational Data Mining in Afghanistan: Opportunities and Ch...
Applicability of Educational Data Mining in Afghanistan: Opportunities and Ch...Applicability of Educational Data Mining in Afghanistan: Opportunities and Ch...
Applicability of Educational Data Mining in Afghanistan: Opportunities and Ch...
Abdul Rahman Sherzad
 
Web Application Security and Awareness
Web Application Security and AwarenessWeb Application Security and Awareness
Web Application Security and Awareness
Abdul Rahman Sherzad
 
Evaluation of Existing Web Structure of Afghan Universities
Evaluation of Existing Web Structure of Afghan UniversitiesEvaluation of Existing Web Structure of Afghan Universities
Evaluation of Existing Web Structure of Afghan Universities
Abdul Rahman Sherzad
 
PHP Basic and Fundamental Questions and Answers with Detail Explanation
PHP Basic and Fundamental Questions and Answers with Detail ExplanationPHP Basic and Fundamental Questions and Answers with Detail Explanation
PHP Basic and Fundamental Questions and Answers with Detail Explanation
Abdul Rahman Sherzad
 
Fundamentals of Database Systems Questions and Answers
Fundamentals of Database Systems Questions and AnswersFundamentals of Database Systems Questions and Answers
Fundamentals of Database Systems Questions and Answers
Abdul Rahman Sherzad
 
Everything about Database JOINS and Relationships
Everything about Database JOINS and RelationshipsEverything about Database JOINS and Relationships
Everything about Database JOINS and Relationships
Abdul Rahman Sherzad
 
Create Splash Screen with Java Step by Step
Create Splash Screen with Java Step by StepCreate Splash Screen with Java Step by Step
Create Splash Screen with Java Step by Step
Abdul Rahman Sherzad
 
Fal-e-Hafez (Omens of Hafez) Cards in Persian using Java
Fal-e-Hafez (Omens of Hafez) Cards in Persian using JavaFal-e-Hafez (Omens of Hafez) Cards in Persian using Java
Fal-e-Hafez (Omens of Hafez) Cards in Persian using Java
Abdul Rahman Sherzad
 
Web Design and Development Life Cycle and Technologies
Web Design and Development Life Cycle and TechnologiesWeb Design and Development Life Cycle and Technologies
Web Design and Development Life Cycle and Technologies
Abdul Rahman Sherzad
 
Java Virtual Keyboard Using Robot, Toolkit and JToggleButton Classes
Java Virtual Keyboard Using Robot, Toolkit and JToggleButton ClassesJava Virtual Keyboard Using Robot, Toolkit and JToggleButton Classes
Java Virtual Keyboard Using Robot, Toolkit and JToggleButton Classes
Abdul Rahman Sherzad
 
Java Unicode with Live GUI Examples
Java Unicode with Live GUI ExamplesJava Unicode with Live GUI Examples
Java Unicode with Live GUI Examples
Abdul Rahman Sherzad
 
Ad

Recently uploaded (20)

SPRING FESTIVITIES - UK AND USA -
SPRING FESTIVITIES - UK AND USA            -SPRING FESTIVITIES - UK AND USA            -
SPRING FESTIVITIES - UK AND USA -
Colégio Santa Teresinha
 
Understanding P–N Junction Semiconductors: A Beginner’s Guide
Understanding P–N Junction Semiconductors: A Beginner’s GuideUnderstanding P–N Junction Semiconductors: A Beginner’s Guide
Understanding P–N Junction Semiconductors: A Beginner’s Guide
GS Virdi
 
Biophysics Chapter 3 Methods of Studying Macromolecules.pdf
Biophysics Chapter 3 Methods of Studying Macromolecules.pdfBiophysics Chapter 3 Methods of Studying Macromolecules.pdf
Biophysics Chapter 3 Methods of Studying Macromolecules.pdf
PKLI-Institute of Nursing and Allied Health Sciences Lahore , Pakistan.
 
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Library Association of Ireland
 
Anti-Depressants pharmacology 1slide.pptx
Anti-Depressants pharmacology 1slide.pptxAnti-Depressants pharmacology 1slide.pptx
Anti-Depressants pharmacology 1slide.pptx
Mayuri Chavan
 
GDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptxGDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptx
azeenhodekar
 
Exploring-Substances-Acidic-Basic-and-Neutral.pdf
Exploring-Substances-Acidic-Basic-and-Neutral.pdfExploring-Substances-Acidic-Basic-and-Neutral.pdf
Exploring-Substances-Acidic-Basic-and-Neutral.pdf
Sandeep Swamy
 
How to Set warnings for invoicing specific customers in odoo
How to Set warnings for invoicing specific customers in odooHow to Set warnings for invoicing specific customers in odoo
How to Set warnings for invoicing specific customers in odoo
Celine George
 
Metamorphosis: Life's Transformative Journey
Metamorphosis: Life's Transformative JourneyMetamorphosis: Life's Transformative Journey
Metamorphosis: Life's Transformative Journey
Arshad Shaikh
 
One Hot encoding a revolution in Machine learning
One Hot encoding a revolution in Machine learningOne Hot encoding a revolution in Machine learning
One Hot encoding a revolution in Machine learning
momer9505
 
Operations Management (Dr. Abdulfatah Salem).pdf
Operations Management (Dr. Abdulfatah Salem).pdfOperations Management (Dr. Abdulfatah Salem).pdf
Operations Management (Dr. Abdulfatah Salem).pdf
Arab Academy for Science, Technology and Maritime Transport
 
To study the nervous system of insect.pptx
To study the nervous system of insect.pptxTo study the nervous system of insect.pptx
To study the nervous system of insect.pptx
Arshad Shaikh
 
The ever evoilving world of science /7th class science curiosity /samyans aca...
The ever evoilving world of science /7th class science curiosity /samyans aca...The ever evoilving world of science /7th class science curiosity /samyans aca...
The ever evoilving world of science /7th class science curiosity /samyans aca...
Sandeep Swamy
 
Unit 6_Introduction_Phishing_Password Cracking.pdf
Unit 6_Introduction_Phishing_Password Cracking.pdfUnit 6_Introduction_Phishing_Password Cracking.pdf
Unit 6_Introduction_Phishing_Password Cracking.pdf
KanchanPatil34
 
How to Customize Your Financial Reports & Tax Reports With Odoo 17 Accounting
How to Customize Your Financial Reports & Tax Reports With Odoo 17 AccountingHow to Customize Your Financial Reports & Tax Reports With Odoo 17 Accounting
How to Customize Your Financial Reports & Tax Reports With Odoo 17 Accounting
Celine George
 
YSPH VMOC Special Report - Measles Outbreak Southwest US 4-30-2025.pptx
YSPH VMOC Special Report - Measles Outbreak  Southwest US 4-30-2025.pptxYSPH VMOC Special Report - Measles Outbreak  Southwest US 4-30-2025.pptx
YSPH VMOC Special Report - Measles Outbreak Southwest US 4-30-2025.pptx
Yale School of Public Health - The Virtual Medical Operations Center (VMOC)
 
Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025
Mebane Rash
 
P-glycoprotein pamphlet: iteration 4 of 4 final
P-glycoprotein pamphlet: iteration 4 of 4 finalP-glycoprotein pamphlet: iteration 4 of 4 final
P-glycoprotein pamphlet: iteration 4 of 4 final
bs22n2s
 
Presentation on Tourism Product Development By Md Shaifullar Rabbi
Presentation on Tourism Product Development By Md Shaifullar RabbiPresentation on Tourism Product Development By Md Shaifullar Rabbi
Presentation on Tourism Product Development By Md Shaifullar Rabbi
Md Shaifullar Rabbi
 
YSPH VMOC Special Report - Measles Outbreak Southwest US 5-3-2025.pptx
YSPH VMOC Special Report - Measles Outbreak  Southwest US 5-3-2025.pptxYSPH VMOC Special Report - Measles Outbreak  Southwest US 5-3-2025.pptx
YSPH VMOC Special Report - Measles Outbreak Southwest US 5-3-2025.pptx
Yale School of Public Health - The Virtual Medical Operations Center (VMOC)
 
Understanding P–N Junction Semiconductors: A Beginner’s Guide
Understanding P–N Junction Semiconductors: A Beginner’s GuideUnderstanding P–N Junction Semiconductors: A Beginner’s Guide
Understanding P–N Junction Semiconductors: A Beginner’s Guide
GS Virdi
 
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Library Association of Ireland
 
Anti-Depressants pharmacology 1slide.pptx
Anti-Depressants pharmacology 1slide.pptxAnti-Depressants pharmacology 1slide.pptx
Anti-Depressants pharmacology 1slide.pptx
Mayuri Chavan
 
GDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptxGDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptx
azeenhodekar
 
Exploring-Substances-Acidic-Basic-and-Neutral.pdf
Exploring-Substances-Acidic-Basic-and-Neutral.pdfExploring-Substances-Acidic-Basic-and-Neutral.pdf
Exploring-Substances-Acidic-Basic-and-Neutral.pdf
Sandeep Swamy
 
How to Set warnings for invoicing specific customers in odoo
How to Set warnings for invoicing specific customers in odooHow to Set warnings for invoicing specific customers in odoo
How to Set warnings for invoicing specific customers in odoo
Celine George
 
Metamorphosis: Life's Transformative Journey
Metamorphosis: Life's Transformative JourneyMetamorphosis: Life's Transformative Journey
Metamorphosis: Life's Transformative Journey
Arshad Shaikh
 
One Hot encoding a revolution in Machine learning
One Hot encoding a revolution in Machine learningOne Hot encoding a revolution in Machine learning
One Hot encoding a revolution in Machine learning
momer9505
 
To study the nervous system of insect.pptx
To study the nervous system of insect.pptxTo study the nervous system of insect.pptx
To study the nervous system of insect.pptx
Arshad Shaikh
 
The ever evoilving world of science /7th class science curiosity /samyans aca...
The ever evoilving world of science /7th class science curiosity /samyans aca...The ever evoilving world of science /7th class science curiosity /samyans aca...
The ever evoilving world of science /7th class science curiosity /samyans aca...
Sandeep Swamy
 
Unit 6_Introduction_Phishing_Password Cracking.pdf
Unit 6_Introduction_Phishing_Password Cracking.pdfUnit 6_Introduction_Phishing_Password Cracking.pdf
Unit 6_Introduction_Phishing_Password Cracking.pdf
KanchanPatil34
 
How to Customize Your Financial Reports & Tax Reports With Odoo 17 Accounting
How to Customize Your Financial Reports & Tax Reports With Odoo 17 AccountingHow to Customize Your Financial Reports & Tax Reports With Odoo 17 Accounting
How to Customize Your Financial Reports & Tax Reports With Odoo 17 Accounting
Celine George
 
Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025
Mebane Rash
 
P-glycoprotein pamphlet: iteration 4 of 4 final
P-glycoprotein pamphlet: iteration 4 of 4 finalP-glycoprotein pamphlet: iteration 4 of 4 final
P-glycoprotein pamphlet: iteration 4 of 4 final
bs22n2s
 
Presentation on Tourism Product Development By Md Shaifullar Rabbi
Presentation on Tourism Product Development By Md Shaifullar RabbiPresentation on Tourism Product Development By Md Shaifullar Rabbi
Presentation on Tourism Product Development By Md Shaifullar Rabbi
Md Shaifullar Rabbi
 

Database Automation with MySQL Triggers and Event Schedulers

  • 1. S e m i n a r o n D a t a b a s e A u t o m a t i o n w i t h M y S Q L T r i g g e r s a n d E v e n t S c h e d u l e r s A b d u l R a h m a n S h e r z a d L e c t u r e r a t C o m p u t e r S c i e n c e f a c u l t y o f H e r a t U n i v e r s i t y , A f g h a n i s t a n P h D S t u d e n t a t T U - B e r l i n , G e r m a n y J a n u a r y 2 7 , 2 0 1 5
  • 2. MySQL Triggers and Events • MySQL Triggers are operations that are automatically performed when a specified database event (INSERT, UPDATE, DELETE) occurs. • Ideally, triggers should be considered when they automate changes which are specific to the database or management of its data. – Data integrity, logging and auditing, business logic, perform calculations, run further SQL commands, etc. • MySQL Events can be scheduled to run once or more during specific periods. Effectively, they are database-only cron-jobs and can be used in many cases such as: – optimizing database tables, archiving data, cleaning up logs, or generate complex reports during off-peak time. 2
  • 4. Introduction to MySQL Triggers • A trigger is a set of SQL statements that is invoked or fired automatically when a change is made to the data on the associated table either before or after the data is changed by DML statements (INSERT, UPDATE or DELETE). • MySQL version 5.7.2 allows you to define maximum six triggers for each table. – BEFORE INSERT – AFTER INSERT – BEFORE UPDATE – AFTER UPDATE – BEFORE DELETE – AFTER DELETE MySQL 5.7.2+ removes this limitation and allows creation of multiple triggers for the same event and action time in a table. 4
  • 5. Introduction to MySQL Triggers II • The trigger is not invoked with statement that makes change to the table but does not use INSERT, DELETE or UPDATE statement. – For example, the TRUNCATE statement removes the whole data of a table but does not invoke the trigger associated with that table. • The triggers are invoked with statements that use the INSERT statement behind the scenes. – For example, REPLACE statement and LOAD DATA statement. • Database triggers are special types of stored procedures. – Special because they are not called explicitly like stored procedures. • Triggers are supported in MySQL, PostgreSQL, SQLite, Firebird, DB2, Microsoft SQL Server and Oracle. – Implementation varies, therefore, the appropriate documentation before coding should be checked. 5
  • 6. MySQL Triggers Advantages • SQL triggers provide an alternative way to check the integrity of data. • SQL triggers provide an alternative way to run scheduled tasks. – By using SQL triggers, no need to wait to run the scheduled tasks because the triggers are invoked automatically before or after a change is made to the data in tables. • SQL triggers are very useful to log and audit the changes of data in tables. Disadvantages • SQL triggers only can provide an extended validation and they cannot replace all the validations. Some simple validations have to be done in the application layer. For example, user's inputs can be validated on the client side or server side. • SQL triggers are invoked and executed invisibly from client-applications therefore it is difficult to figure out what happen in the database layer. • SQL triggers may increase the overhead of the database server. 6
  • 7. Caution!!! • Triggers should not be used in place of foreign key constraints. • Triggers are not a substitute for transactions. • Avoid duplication of effort. – The back-end code should be sanitizing user input so it should not be necessary to repeat those checks within the database. • Triggers will execute quicker than a series of SQL commands passed by back-end code – but using complex triggers on regularly modified tables should be avoided. 7
  • 8. MySQL Trigger Limitation • MySQL triggers cover all features defined in the standard SQL. However, triggers cannot use: – SHOW, LOAD DATA, LOAD TABLE, BACKUP DATABASE, RESTORE, FLUSH and RETURN statements. – Statements that commit or rollback implicitly or explicitly such as COMMIT, ROLLBACK, START TRANSACTION, LOCK / UNLOCK TABLES, ALTER, CREATE, DROP, RENAME, etc. – Prepared statements such as PREPARE, EXECUTE, etc. – Dynamic SQL statements. MySQL version 5.1.4+ a trigger can call a stored procedure or stored function, which was a limitation is the previous versions. 8
  • 9. MySQL Trigger Storage and Backup • MySQL stores triggers in a data directory e.g. /data/database_name/ with the files named table_name.TRG and trigger_name.TRN – The table_name.TRG file maps the trigger to the corresponding table. – the trigger_name.TRN file contains the trigger definition. • To back up the MySQL triggers – Copy the trigger files to the backup directory. – Use the mysqldump tool. 9
  • 10. Create MySQL Trigger Basic Syntax 10 CREATE TRIGGER trigger_name trigger_time trigger_event ON table_name FOR EACH ROW BEGIN -- the trigger body -- this code is applied to every -- inserted/updated/deleted row END;
  • 11. Create MySQL Trigger Syntax Details • The trigger name comes after the CREATE TRIGGER statement. – The trigger name should follow the naming convention [table name]_[trigger time]_ [trigger event]. • Trigger activation time can be BEFORE or AFTER. • The trigger event can be INSERT, UPDATE or DELETE. • The table name must specify after the ON keyword. – A trigger must be associated with a specific table. Without a table trigger would not exist. • The trigger body is a set of SQL commands to run and are placed between BEGIN and END block. This is where the logic for the trigger is defined. 11
  • 12. Notice! • In the trigger defined for INSERT – NEW keyword can be used only. – OLD keyword can not be used. • In the trigger defined for DELETE – there is no new row. Therefore, the OLD keyword can be used only. • In the UPDATE trigger – OLD keyword refers to the row before it is updated. – NEW keyword refers to the row after it is updated. 12
  • 14. MySQL Trigger Application Scenario • A small example database with two tables as follow: – Blog: stores a unique ID, the title, content, and a deleted flag. – Audit: stores a basic set of historical changes with an ID, the blog ID, the old blog title, the change type (NEW, EDIT or DELETE), and the date/time of that change. • INSERT into the blog table – A new entry into the audit table containing the blog ID, the title, and a type of 'NEW' (or 'DELETE' if it was deleted immediately) should be added. • UPDATE in the blog table – A new entry into the audit table containing the blog ID, the title, and a type of 'EDIT' (or 'DELETE' if the deleted flag is set) should be added. The 'changetime' attribute will automatically be set to the current time. 14
  • 16. Blog Schema CREATE TABLE blog ( id INT NOT NULL AUTO_INCREMENT, title VARCHAR(255), content text, deleted TINYINT(1) unsigned NOT NULL DEFAULT '0', PRIMARY KEY (id), KEY (deleted) ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8; 16
  • 17. Audit Schema CREATE TABLE audit ( id INT PRIMARY KEY NOT NULL AUTO_INCREMENT, blog_id INT NOT NULL, blog_title VARCHAR(255) NOT NULL, changetype ENUM('NEW','EDIT','DELETE') NOT NULL, changetime timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, KEY (blog_id), CONSTRAINT FOREIGN KEY (blog_id) REFERENCES blog (id) ON DELETE CASCADE ON UPDATE CASCADE ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8; 17
  • 18. Notice: Delimiter • Most of the time the trigger body requires a number of SQL commands separated by a semi-colon (;). • To create the full trigger code the delimiter must be changed to something else. For example – $$ – // • Finally, after trigger code completion the delimiter back should be set to a semi-colon. 18
  • 19. Trigger: AFTER INSERT DELIMITER $$ CREATE TRIGGER blog_after_insert AFTER INSERT ON blog FOR EACH ROW BEGIN IF NEW.deleted THEN SET @changetype = 'DELETE'; ELSE SET @changetype = 'NEW'; END IF; INSERT INTO audit (blog_id, blog_title, changetype) VALUES (NEW.id, NEW.title, @changetype); END; $$ DELIMITER ; 19
  • 20. Trigger: AFTER UPDATE DELIMITER $$ CREATE TRIGGER blog_after_update AFTER UPDATE ON blog FOR EACH ROW BEGIN IF NEW.deleted THEN SET @changetype = 'DELETE'; ELSE SET @changetype = 'EDIT'; END IF; INSERT INTO audit (blog_id, blog_title, changetype) VALUES (NEW.id, OLD.title, @changetype); END; $$ DELIMITER ; 20
  • 21. Test the Triggers • Let's see what happens when we insert a new post into our blog table: INSERT INTO blog (title, content) VALUES ('First blog', 'The first blog content'); SELECT * FROM blog; SELECT * FROM audit; • Let's update our blog text: UPDATE blog SET title = 'First blog Edited' WHERE id = 1; SELECT * FROM audit; • Finally, let's mark the post as deleted: UPDATE blog SET deleted = 1 WHERE id = 1; SELECT * FROM audit; 21
  • 23. Introduction to MySQL Events • MySQL events were added in MySQL 5.1.6 and offer an alternative to scheduled tasks and cron jobs. • Events can be used to create backups, delete out-of-date and old records, aggregate data for reports, etc. • Unlike standard triggers which execute given a certain condition, an event is an object that is triggered by the passage of time and is sometimes referred to as a 'temporal trigger'. • MySQL events can be scheduled to run either once or at a recurring interval – when the server traffic will be low. 23
  • 24. Starting the Event Scheduler • The MySQL event scheduler is a process that runs in the background and constantly looks for events to execute. • Before creating or scheduling an event, first the scheduler needs to turn on, with issuing the following command: SET GLOBAL event_scheduler = ON; • With the following the scheduler status is revealed if it is ON or OFF: SHOW PROCESSLIST; 24
  • 25. Create MySQL Event Basic Syntax CREATE EVENT event_name ON SCHEDULE the_schedule [ON COMPLETION [NOT] PRESERVE] [ENABLE | DISABLE | DISABLE ON SLAVE] DO BEGIN -- the event body END; 25
  • 26. The Schedule Settings • Run once on a specific date/time: – AT 'YYYY-MM-DD HH:MM.SS' • AT '2016-01-15 02:00.00' • Run once after a specific period has elapsed: – AT CURRENT_TIMESTAMP + INTERVAL n [HOUR|MONTH|WEEK|DAY|MINUTE] • AT CURRENT_TIMESTAMP + INTERVAL 1 DAY • Run at specific intervals forever: – EVERY n [HOUR|MONTH|WEEK|DAY|MINUTE] • EVERY 1 DAY • Run at specific intervals during a specific period: – EVERY n [HOUR|MONTH|WEEK|DAY|MINUTE] STARTS date ENDS date • EVERY 1 DAY STARTS CURRENT_TIMESTAMP + INTERVAL 1 WEEK ENDS '2017-01-01 00:00.00' 26
  • 27. Caution!!! • An event is normally dropped once its schedule has expired – ON COMPLETION NOT PRESERVE • To prevent that behavior set – ON COMPLETION PRESERVE 27
  • 28. Run Once Event Example DELIMITER $$ CREATE EVENT one_time_event_example ON SCHEDULE AT CURRENT_TIMESTAMP + INTERVAL 5 MINUTE DO BEGIN UPDATE blog SET title = "One time event example" WHERE id = 1; END; $$ DELIMITER ; • This event will run once, one hour from the time it was created. 28
  • 29. Preserved Event Example DELIMITER $$ CREATE EVENT preserved_event_example ON SCHEDULE AT CURRENT_TIMESTAMP + INTERVAL 1 HOUR ON COMPLETION PRESERVE DO BEGIN UPDATE blog SET title = "Preserve event example" WHERE id = 1; END; $$ DELIMITER ; • To specify a preserved event, the ON COMPLETION PRESERVE clause must be used. 29
  • 30. Reoccurring Event Example DELIMITER $$ CREATE EVENT reoccurring_event_example ON SCHEDULE EVERY 1 HOUR DO BEGIN UPDATE blog SET title = "Reoccurring event example" WHERE id = 1; END; $$ DELIMITER ; • To specify a recurring event, the EVERY clause must be used. • In this example, the reoccurring event would start tomorrow and continue to run every hour for a full year. 30
  • 32. MySQL Event Application Scenario • The database example used for trigger application has a problem. – The old blog posts are marked as deleted rather than being removed from the blog table. – The blog table will grow indefinitely and become slower over time. – The old blog posts could be purged, but that would remove them forever. • As a result, we will move the blog posts and their associated audit records to archive tables. – The archive tables can grow without affecting the speed of the main web application and we can undelete the old blog posts if necessary. • Two archive tables are required: – blog_archive: identical to the blog table except it does not require a deleted flag or an auto-incrementing ID. – audit_archive: identical to the audit table except the timestamp is not automatically generated and it does not require an auto-incrementing ID. 32
  • 33. MySQL Event Application Scenario II • A scheduled event is required to: – Copies blog posts from blog to blog_archive when the deleted flag is set to 1. – Copies the associated audit entries for those blog posts from audit to audit_archive. – Physically deletes the archived blog posts from the blog table. – Referential integrity has been defined with a foreign key. Therefore, all the associated audit entries for those blog posts will also be removed. 33
  • 35. Blog Archive Schema CREATE TABLE blog_archive ( id INT NOT NULL, title VARCHAR(255), content text, PRIMARY KEY (id) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; 35
  • 36. Audit Archive Schema CREATE TABLE audit_archive ( id INT PRIMARY KEY NOT NULL, blog_id INT NOT NULL, blog_title VARCHAR(255), changetype ENUM('NEW','EDIT','DELETE') NOT NULL, changetime timestamp NOT NULL, KEY (blog_id), CONSTRAINT FOREIGN KEY (blog_id) REFERENCES blog_archive (id) ON DELETE CASCADE ON UPDATE CASCADE ) ENGINE=InnoDB DEFAULT CHARSET=utf8; 36
  • 37. The Archive Event DELIMITER $$ CREATE EVENT archive_blog_posts ON SCHEDULE EVERY 1 WEEK STARTS '2016-01-22 01:00:00' DO BEGIN -- copy deleted posts INSERT INTO blog_archive (id, title, content) SELECT id, title, content FROM blog WHERE deleted = 1; -- copy associated audit records INSERT INTO audit_archive (id, blog_id, blog_title, changetype, changetime) SELECT audit.id, audit.blog_id, audit.blog_title, audit.changetype, audit.changetime FROM audit JOIN blog ON audit.blog_id = blog.id WHERE blog.deleted = 1; -- remove deleted blogs and audit entries DELETE FROM blog WHERE deleted = 1; END; $$ DELIMITER ; • In the example, the event runs every week on Friday morning. 37
  • 38. Wrap up • The Triggers are powerful tools for protecting the integrity of the data in the databases – Data integrity, logging and auditing, business logic, perform calculations, run further SQL commands, etc. • The Events are very useful to automate some database operations – optimizing database tables, cleaning up logs, archiving data, or generate complex reports during off-peak time. 38
  • 39. Abdul Rahman Sherzad • Thank you for your participation – Herat University – Hariwa Institute of Higher Education – Ghalib University – Khaja Abdullah Ansari Institute of Higher Education – ICT Companies Lecturer at Computer Science faculty of Herat University, Afghanistan. PhD Student at Technical University of Berlin (TU-Berlin), Germany. January 27, 2015 39
  • 40. 40
  • 41. 41
  • 42. 42