0% found this document useful (0 votes)
58 views32 pages

Fundamentals of Database Systems: (SQL - V)

The document outlines how to create triggers in MySQL to enforce advanced integrity constraints and automate database operations. Triggers are stored programs that execute automatically in response to data changes like inserts, updates or deletes. They can contain conditional logic and access old and new data values using OLD and NEW keywords. Variables can be declared and assigned values within triggers.

Uploaded by

thecoolguy96
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
58 views32 pages

Fundamentals of Database Systems: (SQL - V)

The document outlines how to create triggers in MySQL to enforce advanced integrity constraints and automate database operations. Triggers are stored programs that execute automatically in response to data changes like inserts, updates or deletes. They can contain conditional logic and access old and new data values using OLD and NEW keywords. Variables can be declared and assigned values within triggers.

Uploaded by

thecoolguy96
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 32

Outline Advanced Integrity Preservation Cursors Problems

Fundamentals of Database Systems


[SQL – V]

Malay Bhattacharyya

Assistant Professor

Machine Intelligence Unit


Indian Statistical Institute, Kolkata
December, 2020
Outline Advanced Integrity Preservation Cursors Problems

1 Advanced Integrity Preservation


Basics
Creating Triggers
Creating Multiple Triggers
Limitations

2 Cursors

3 Problems
Outline Advanced Integrity Preservation Cursors Problems

Advanced integrity constraints

The advanced integrity constraints can be specified with triggers.


It protects the integrity of data in databases and is also useful to
automate some database operations such as logging, auditing, etc.

A trigger (or database trigger) is a stored program that executes


automatically in response to a specific event. E.g., insert, update
or delete occurred in a table.

Note: An SQL trigger is a set of SQL statements that are stored


in the database catalog.
Outline Advanced Integrity Preservation Cursors Problems

Triggers in MySQL

One can define at most six triggers for each table. These are
activated in coordination with the following events.
BEFORE INSERT - before data is inserted into the table.
AFTER INSERT - after data is inserted into the table.
BEFORE UPDATE - before data in the table is updated.
AFTER UPDATE - after data in the table is updated.
BEFORE DELETE - before data is removed from the table.
AFTER DELETE - after data is removed from the table.

Note: For MySQL version 5.7.2+, one can define multiple triggers
for the same trigger event and action time.
Outline Advanced Integrity Preservation Cursors Problems

Triggers in MySQL

To display all the triggers in the database, the following SQL query
is used:
show triggers;

To delete a particular trigger from the database, the following SQL


query is used:
drop trigger <trigger name>;

Note: One must have MySQL SUPERUSER privileges for running


trigger.
Outline Advanced Integrity Preservation Cursors Problems

Creating triggers in MySQL


A trigger must be associated with a specific table and is written as:
create trigger <trigger name>
<trigger time> <trigger event> on <table name>
for each row
<Triggered SQL statement>;

The trigger time can be before/after.


The trigger event can be insert/update/delete.
The clause for each row says that the trigger activation will
occur for the rows of the table, not for the table as a whole.
The logic for the trigger is placed as a block of SQL
statements.

Note: Delimiters are required in some interfaces (e.g. MySQL


client).
Outline Advanced Integrity Preservation Cursors Problems

Creating triggers in MySQL – Compound statements

A trigger can accommodate compound SQL statements as follows:


create trigger <trigger name>
<trigger time> <trigger event> on <table name>
for each row
begin
<Triggered SQL statement(s)>
end;

Note: The begin-end block can take multiple SQL statements.


Outline Advanced Integrity Preservation Cursors Problems

Creating triggers in MySQL – OLD and NEW keywords

Due to the changes in a table due to triggering, there might be


some new attributes as well as some old ones. Therefore, within a
triggered SQL statement, attributes are explicitly referred to as
NEW.<attribute name> or OLD.<attribute name>.

With insert, only NEW is legal.


With delete, only OLD is legal.
With update, both NEW and OLD are legal.

Note: The objects NEW.<attribute name> and


OLD.<attribute name> are referred to as transition variables.
Outline Advanced Integrity Preservation Cursors Problems

Creating triggers in MySQL – OLD and NEW keywords

Table: FACULTY
ID NAME EMAIL AGE
1 Debasis Sengupta [email protected] 60
2 Debapriyo Majumdar [email protected] 40
3 Malay Bhattacharyya [email protected] 37
Outline Advanced Integrity Preservation Cursors Problems

Creating triggers in MySQL – OLD and NEW keywords

Table: FACULTY
ID NAME EMAIL AGE
1 Debasis Sengupta [email protected] 60
2 Debapriyo Majumdar [email protected] 40
3 Malay Bhattacharyya [email protected] 37

Consider the following table to keep the update details on the


FACULTY table.
create table FACULTY LOG(
ID int auto increment primary key,
NAME varchar(50) not null,
LOGTIME datetime default null,
ACTION varchar(50) default null
);
Outline Advanced Integrity Preservation Cursors Problems

Creating triggers in MySQL – OLD and NEW keywords

Triggers can be set to act on the FACULTY LOG table before


making updates on the FACULTY table as follows.

create trigger before FACULTY update


before update on FACULTY
for each row
insert into FACULTY LOG values (OLD.ID, OLD.NAME,
NOW(), ‘Update’);

Note: We use the OLD keyword to access ID and NAME attributes


of the tuples affected by the trigger.
Outline Advanced Integrity Preservation Cursors Problems

Creating triggers in MySQL – OLD and NEW keywords

Consider the following SQL query that makes an update operation


on the FACULTY table at 00:00:01 AM on February 02, 2021.
update FACULTY set AGE = 38 where NAME = "Malay
Bhattacharyya";
Outline Advanced Integrity Preservation Cursors Problems

Creating triggers in MySQL – OLD and NEW keywords

Consider the following SQL query that makes an update operation


on the FACULTY table at 00:00:01 AM on February 02, 2021.
update FACULTY set AGE = 38 where NAME = "Malay
Bhattacharyya";

This will make the following entry to the FACULTY LOG table:

Table: FACULTY LOG


ID NAME LOGTIME ACTION
3 Malay Bhattacharyya 2021-02-02 00:00:01 Update
Outline Advanced Integrity Preservation Cursors Problems

Creating triggers in MySQL – Variable declaration

Variables can be declared as follows.

declare Age, Experience int default 0;


declare Name varchar(50);
declare Today date default current date;
declare Var1, Var2, Var3 double(10,2);
Outline Advanced Integrity Preservation Cursors Problems

Creating triggers in MySQL – Variable assignment

Values can be assigned to variables as follows.

set var1 = 101;


set str1 = ‘Hello world’;
set v1 = 19.99;
Outline Advanced Integrity Preservation Cursors Problems

Creating triggers in MySQL – Handler declarations

The handler statements deal with one or more conditions. If one of


these conditions occurs, the specified statement executes. To
declare handlers, the following SQL query is used:
declare <handler action> handler for <condition value>
<statement>;

The <handler action> can be continue/exit/undo.


The <condition value> can be
mysql error code/sqlstate/sqlwarning/sqlexception/not
found.
Outline Advanced Integrity Preservation Cursors Problems

Creating triggers in MySQL – Conditional flow

The if-else construct works as follows.

if <condition> then
<statement>;
else
<statement>;
end if;
Outline Advanced Integrity Preservation Cursors Problems

Creating triggers in MySQL – Conditional flow

Consider the following table that stores names, ages and course
names of some students.

create table STUDENT(


AGE int,
NAME varchar(50),
COURSE varchar(50)
);
Outline Advanced Integrity Preservation Cursors Problems

Creating triggers in MySQL – Conditional flow

Triggers can be set to act on the Age attribute for non-negativity


check before making insertions in the STUDENT table as follows.
create trigger agecheck
before insert on STUDENT
for each row
begin
if NEW.AGE < 0 then
set NEW.AGE = abs(NEW.AGE);
end if
end;

Note: We use the NEW keyword to access the new values inserted
in the table.
Outline Advanced Integrity Preservation Cursors Problems

Creating triggers in MySQL – Conditional flow

Consider the following SQL query:


insert into STUDENT values (25, ‘Hemanth’, ‘PGDBA’),
(24, ‘Vemula’, ‘PGDBA’), (-26, ‘Sidhant’, ‘PGDBA’),
(24, ‘Hitesh’, ‘PGDBA’);

This will turn the STUDENT table as follows.

Table: STUDENT
AGE NAME COURSE
25 Hemanth PGDBA
24 Vemula PGDBA
26 Sidhant PGDBA
24 Hitesh PGDBA
Outline Advanced Integrity Preservation Cursors Problems

Creating triggers in MySQL – Repetitive flow

The loop construct works as follows.

<loop name>: loop


<statement>;
if <condition> then
<statement>;
leave <loop name>;
end if;
<statement>
end loop <loop name>;
Outline Advanced Integrity Preservation Cursors Problems

Creating triggers in MySQL – Repetitive flow

The while construct works as follows.

<loop name>: while <condition> do


<statement>
if <condition> then
leave <loop name>;
end if;
<statement>
end while;
Outline Advanced Integrity Preservation Cursors Problems

Creating triggers in MySQL – Repetitive flow

The repeat-until construct works as follows.

<loop name>: repeat


<statement>;
if <condition> then
<statement>;
leave <loop name>;
end if;
<statement>;
until <condition> end repeat;

Note: The repetitive block executes once irrespective of the


<condition>.
Outline Advanced Integrity Preservation Cursors Problems

Creating multiple triggers in MySQL

Multiple triggers are written as follows:

delimiter $$ -- The end delimiter is now ‘$$’


create trigger <trigger name>
<trigger time> <trigger event> on <table name>
for each row
<Triggered SQL statement> -- Works well with ‘;’
create trigger <trigger name>
<trigger time> <trigger event> on <table name>
for each row
begin
<Triggered SQL statement(s)> -- Works well with ‘;’
end;
$$
delimiter ; -- The delimiter is changed back to ‘;’
Outline Advanced Integrity Preservation Cursors Problems

Limitations of triggers in MySQL

A MySQL trigger cannot perform the following things:


Using SHOW, LOAD DATA, LOAD TABLE, BACKUP
DATABASE, RESTORE, FLUSH, RETURN statements.
Using statements that commit or rollback implicitly or
explicitly such as COMMIT, ROLLBACK, START
TRANSACTION, LOCK/UNLOCK TABLES, ALTER, CREATE,
DROP, RENAME.
Using prepared statements such as PREPARE, EXECUTE.
Using dynamic SQL statements.
Outline Advanced Integrity Preservation Cursors Problems

Basics of cursors
A cursor allows to iterate a set of rows returned by a query and
process each row accordingly. It is used to handle a result set
inside a stored procedure.
MySQL cursors have the following properties:
Read-only: Cursors cannot be used to update data in the
underlying table.
Non-scrollable: Rows can only be fetched in the order
determined by the select statement. One cannot skip rows or
jump to a specific row in the result set.
Asensitive: MySQL cursors are asensitive. It is often faster
because it does not need to make a temporary copy of data.
Outline Advanced Integrity Preservation Cursors Problems

Basics of cursors
A cursor allows to iterate a set of rows returned by a query and
process each row accordingly. It is used to handle a result set
inside a stored procedure.
MySQL cursors have the following properties:
Read-only: Cursors cannot be used to update data in the
underlying table.
Non-scrollable: Rows can only be fetched in the order
determined by the select statement. One cannot skip rows or
jump to a specific row in the result set.
Asensitive: MySQL cursors are asensitive. It is often faster
because it does not need to make a temporary copy of data.

Note: Cursors are of two types – asensitive and insensitive. An


asensitive cursor points to the actual data, whereas an insensitive
cursor uses a temporary copy of the data. It is safer not to update
the data used by an asensitive cursor.
Outline Advanced Integrity Preservation Cursors Problems

Creating cursors

To define a cursor, the following SQL query is used:


declare <cursor name> cursor for <select statement>;

To initialize the result set for the cursor, before fetching rows from
the result set, the following SQL query is used:
open <cursor name>;

To retrieve the next row pointed by the cursor and move the cursor
to the next row in the result set, the following SQL query is used:
fetch <cursor name> into <list variables>;

To close a cursor, the following SQL query is used:


close <cursor name>;
Outline Advanced Integrity Preservation Cursors Problems

Data handling with cursors

The entire life cycle of an MySQL cursor is illustrated in the


following diagram.
Outline Advanced Integrity Preservation Cursors Problems

Data handling with cursors – An example

Suppose we want to build an email list of all employees from the


FACULTY table.
Let us first declare some variables, a cursor for looping over the
emails of employees, and a NOT FOUND handler.

declare Var Done int default 0;


declare email varchar(500) default "";
declare email cursor cursor for select email from
FACULTY;
declare continue handler for not found set Var Done =
1;
Outline Advanced Integrity Preservation Cursors Problems

Data handling with cursors – An example

Now, open the email cursor as follows:


open email cursor;
Then, iterate the email list, and concatenate all the emails where
each email is separated by a semicolon as follows:
get email: loop
fetch email cursor into email;
if Var Done = 1 then
leave get email;
end if;
set email list = concat(email,";",email list);
end loop get email;
Outline Advanced Integrity Preservation Cursors Problems

Problems

1 Consider the following schema of an online code repository


system like GitHub:
Contributor =
hcontributor name : string , contributor id : integer i
Code-Group = hcontributor id : integer , code group :
string , count submissions : integer i
Write an SQL trigger to restrict all the possible events that
can make violations to the above schema.

You might also like