0% found this document useful (0 votes)
154 views47 pages

Database Systems - BIT University of Colombo

The document discusses Database Systems II course content including stored procedures, triggers, data storage and querying, transaction management, and distributed databases. It provides learning outcomes, syllabus outline, and references. The first topic covers constraints and triggers, describing different constraint types like primary key, foreign key, unique, check, and default constraints. It also defines triggers, their types, timing, and syntax for creating them in SQL. Triggers can be used to automatically execute code in response to data changes.

Uploaded by

Amali
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)
154 views47 pages

Database Systems - BIT University of Colombo

The document discusses Database Systems II course content including stored procedures, triggers, data storage and querying, transaction management, and distributed databases. It provides learning outcomes, syllabus outline, and references. The first topic covers constraints and triggers, describing different constraint types like primary key, foreign key, unique, check, and default constraints. It also defines triggers, their types, timing, and syntax for creating them in SQL. Triggers can be used to automatically execute code in response to data changes.

Uploaded by

Amali
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/ 47

IT6405: Database

Systems II
BIT – 3rd Year
Semester 6
IT6405: Database Systems II

Learning Outcome
After successful completion of this
course students will be able to:
– create stored procedures and triggers
– describe data storage & access and
manipulate query processing techniques
– demonstrate transaction processing
techniques of database systems
– determine designs for distributed databases

UCSC - 2016 2
IT6405: Database Systems II

Outline of Syllabus
1. Stored Procedures and Triggers
2. Data Storage and Querying
3. Transaction Management
4. Distributed Databases

UCSC - 2016 3
IT6405: Database Systems II

References
1. Elmasri, Navathe, Somayajulu, and Gupta,
“Fundamentals of Database Systems”, 5th Edition,
Pearson Education (2008)
Note: 6th Edition released in 2011
2. Silberschatz A., Korth H.F. and Sudarshan S., “Database
System Concepts”, 5th Edition, McGraw Hill (2006).
Note: 6th Edition released in 2010
3. Ramakrishnan, Gehrke, “Database Management
Systems”, 3rd edition, McGraw Hill

UCSC - 2016 4
IT6405: Database Systems II – Topic 1

IT6405: Database Systems II

Stored Procedures and Triggers

Duration: 06 hours

UCSC - 2016 5
IT6405: Database Systems II – Topic 1

Learning Objectives
• Write stored procedures and triggers in
SQL

UCSC - 2016 6
IT6405: Database Systems II – Topic 1

Detailed Syllabus
1.1 Constraints and triggers (03hrs) [REF1: Chapter 1,
5, 26, pg. 21, 132, 933-945]

1.2 Database stored procedures (03hrs) [REF1:


Chapter 13, pg. 473-475]

UCSC - 2016 7
IT6405: Database Systems II – Topic 1

1.1 CONSTRAINTS AND TRIGGERS

UCSC - 2016 8
IT6405: Database Systems II – Topic 1

Data Integrity
• It ensures that the values entering to the
database is accurate and valid
• Uses integrity constraints
• Integrity constraints maintains accurate
databases by eliminating invalid data
updates/ insert/ deletes

UCSC - 2016
Common Database Integrity
Constraints
• Entity integrity does not allow two rows with
the same identity in a table
• Domain integrity allows only predefined
values
• Referential integrity allows only the
consistency of values
across related tables
• User-defined integrity define constraints

UCSC - 2016 10
IT6405: Database Systems II – Topic 1

Database Constraints
• They are the restrictions on the contents of
the database and its operations
• Types of Constraints
– Primary key constraint
– Foreign key constraint (referential integrity)
– Unique constraint
– NOT NULL constraint
– Check Constraint
– Default constraint
UCSC - 2016 11
Primary Key & Unique Constraints
CREATE TABLE Student (
stdid CHAR (10),
name CHAR(20),
address CHAR(25),
age INTEGER,
CONSTRAINT pk_stdID PRIMARY KEY (stdid) );
CREATE TABLE Student (
Stdid CHAR (10) PRIMARY KEY,
Name CHAR(20),
Address CHAR(25),
Age INTEGER,
NIC CHAR(10) UNIQUE );
UCSC - 2016 12
IT6405: Database Systems II – Topic 1

NOT NULL Constraint

CREATE TABLE Student (


Sid Number Primary Key,
Name CHAR(20) NOT NULL,
Address CHAR(25),
Age INTEGER );

UCSC - 2016 13
IT6405: Database Systems II – Topic 1

Foreign Key Constraint


CREATE TABLE Marks (
sid Number,
cid Number,
grade CHAR(2),
PRIMARY KEY(cid,sid),
FOREIGN KEY(sid) REFERENCES Student
CONSTRAINT fk_Grade FOREIGN KEY(sid)
REFERENCES Student(sid) )

UCSC - 2016 14
IT6405: Database Systems II – Topic 1

Default Constraint
CREATE TABLE Student (
Name CHAR(20),
Address CHAR(25),
Department CHAR (20)
DEFAULT ‘Computer Science’,
Age INTEGER
);

UCSC - 2016 15
IT6405: Database Systems II – Topic 1

Check Constraint
CREATE TABLE UnderGrad_Student (
Sid Number Primary Key,
Name CHAR(20),
Address CHAR(25),
Age INTEGER,
Reg_Course CHAR(10),
CHECK (Age BETWEEN 19 AND 26)
);

UCSC - 2016 16
Referential Triggered Action
• Operations
ON DELETE, ON UPDATE
• Actions To Take
SET NULL, CASCADE, SET DEFAULT,
NO ACTION, RESTRICT
CREATE TABLE Employee (
NIC VARCHAR(10) PRIMARY KEY,
name VARCHAR(50) ,
works_in INTEGER,
CONSTRAINT fk_EmpDept FOREIGN KEY
(works_in) REFERENCES Dept ON DELETE
CASCADE ON UPDATE NO ACTION
); UCSC - 2016 17
IT6405: Database Systems II – Topic 1

Drop Tables
The actions to take when Dropping tables

• RESTRICT – if there is constraint (FK / View)


then do not drop the table
• CASCADE - drop all the other constraints &
views that refers the table

DROP TABLE Employee [RESTRICT|CASCADE]

UCSC - 2016 18
IT6405: Database Systems II – Topic 1

Add or Remove Constraints


• Drop a table's primary key constraint
ALTER TABLE Student Drop PRIMARY KEY
• Drop a unique, foreign key, or check constraint
ALTER TABLE Employee Drop Constraint
fk_EmpDept
• Add a new constraint
ALTER TABLE PassStudents
ADD Constraint avg_Marks CHECK(
marks >= 50 )
UCSC - 2016 19
Introduction to Triggers
What is a Trigger?
• It is an event that will run automatically when
there
is a change occur to the database
• Reason to use Triggers
E.g. A production organization maintains a
warehouse. It maintains a minimum inventory
level. When the inventory level goes down
how will the reorder manager identify it at
once?
UCSC - 2016 20
Design a Trigger
• To design a trigger you require to identify;
When should the trigger be executed?
An event – a cause to check the trigger
A condition – logic to be satisfied to
execute the trigger
The action that should be taken when the
trigger is executed

• Model of a trigger also known as event-


condition – action model
UCSC - 2016 21
IT6405: Database Systems II – Topic 1

Triggers
Types of Triggers
• Row Triggers - For each row of the table
trigger is fired
E.g. delete each employee from employee
table whose department is IT
• Statement Triggers - Only once the trigger will
fire
E.g. update salary of every employee working
for the IT department
UCSC - 2016 22
IT6405: Database Systems II – Topic 1

Triggers
• Trigger Timing
Before Trigger – runs before any change is
made to the database.
E.g. if you want to withdraw money from ATM
first need to check account balance before
doing the transaction
• After Trigger - runs after changes are made to
the database
E.g. After withdrawing money update the
account balance
UCSC - 2016 23
IT6405: Database Systems II – Topic 1

Syntax for Specifying a Trigger


<trigger> : CREATE TRIGGER <trigger name>
(AFTER/BEFORE) <triggering events> ON
<table name>
[FOR EACH ROW]
[WHEN <condition>]
<trigger actions>;
<triggering events> : <trigger event>
<trigger event> : INSERT|UPDATE|DELETE [OF
<column name>]
<trigger actions> : <PL/SQL block>
UCSC - 2016 24
Example
• Insert values for following schema. Ensure
that the salary is >= 20000
employee (pNum, pName, salary)
CREATE TRIGGER check_salary
BEFORE INSERT ON employee
FOR EACH ROW
BEGIN
IF (:new.salary < 20000)
THEN
PRINT ‘Wrong Salary’;
END IF;
END; UCSC - 2016 25
IT6405: Database Systems II – Topic 1

Syntax for Creating Statement Triggers


CREATE [OR REPLACE] TRIGGER trigger_name
timing {BEFORE|AFTER|INSTEAD OF}
event1 {DELETE | INSERT | UPDATE}
[OF column1, column2, …]
[OR event2 OR event3] ON table_name
condition
action

timing – when the event would happen such as before an insert


event1 – event such as insert on a table
condition – when to execute the event
action – what actions to be taken

UCSC - 2016 26
CREATE TRIGGER Salary-trigger
BEFORE UPDATE OF Salary ON Employee
condition
action

CREATE TRIGGER Salary-trigger


AFTER DELETE ON Employee
condition
action

CREATE TRIGGER Salary-trigger


INSTEAD OF INSERT ON Employee
condition
action

UCSC - 2016 27
IT6405: Database Systems II – Topic 1

Cascade Delete [row-level]


CREATE TRIGGER Cascade
After Delete On Department
Referencing Old Row As O
For Each Row
Delete from Employee where dept = O.deptID

No explicit Condition for this Trigger. However


when a row is found it is like condition is true
UCSC - 2016 28
IT6405: Database Systems II – Topic 1

Cascade Delete [statement-level]


CREATE TRIGGER Cascade
After Delete On Department
Referencing Old Table As OT
Delete from Employee where dept In
(Select deptID from OT)

No Condition for this Trigger


UCSC - 2016 29
IT6405: Database Systems II – Topic 1

• Postgres
– Row-level
– Statement-level
– old/new row/table
• MySQL
– Row-level only
– No Old/New Table
– For Each Row Implicit
– No Referencing
– Only one trigger per event type
– Limited trigger chaining
UCSC - 2016 30
IT6405: Database Systems II – Topic 1
If GPA (>= 2.5)  eligible for Physics Special
when Update GPA need to identify Eligible students

Student
sID sName gender GPA
Ex
130001 Sunil M 1.63
130002 Anil M 0
130004 Nimali F 3.75

Eligible
sID discipline Major Decision
130004 Physics Physics
130004 Physics Engineering Physics
130004 Physics Computational Physics
UCSC - 2016
create trigger trigger_name
timing event1 on table_name
condition
Ex
action Insert into Student values(
130006, ‘Paul’, ‘M’, 3.5);
Insert into Student values(
Create trigger special 130007, ‘Kevin’, ‘M’, 2.3);
After insert on Student
for each row
when New.GPA >= 2.5 and 65 < (select mark from Marks
where sID = New.sID and cID=‘PH111’)
begin
Insert into Eligible values( New.sID,
‘Physics’, ‘Physics’, null);
Insert into Eligible values( New.sID,
‘Physics’, ‘Engineering Physics’, null);
Insert into Eligible values( New.sID,
‘Physics’, ‘Computational Physics’, null);
end; 32
create trigger trigger_name
timing event1 on table_name
condition
Ex
action

UPDATE Student
Insert into Student values(
SET sName= ‘Paul’
130009, ‘Paul’, ‘M’, 2.5);
WHERE sID = 130009;

Create trigger unique_inst_name


Before update of
Before insert on Student
sName on Student
for each row
when exists(select * from Student
where sName = New.sName)
begin
select raise(ignore) ;
end;

33
IT6405: Database Systems II – Topic 1

Example: Row Level Trigger


CREATE TRIGGER NoLowerPrices

AFTER UPDATE OF price ON Product

REFERENCING
OLD AS OldTuple
NEW AS NewTuple

WHEN (OldTuple.price > NewTuple.price)


UPDATE Product
SET price = OldTuple.price
WHERE name = NewTuple.name

FOR EACH ROW


UCSC - 2016
Statement Level Trigger
CREATE TRIGGER average-price-preserve
INSTEAD OF UPDATE OF price ON Product

REFERENCING
OLD_TABLE AS OldStuff
NEW_TABLE AS NewStuff

WHEN (1000 <


(SELECT AVG (price)
FROM ((Product EXCEPT OldStuff) UNION
NewStuff))

DELETE FROM Product


WHERE (name, price, company) IN OldStuff;

INSERT INTO Product


(SELECT * FROM NewStuff)
Triggers and Alerts
• An alert is a variant of the trigger mechanism.
This is used to notify users of important
events in the database.
Send a message to the head calling to his
attention a purchase transaction for Rs.
10,000 or more made from the department
funds.
CREATE TRIGGER Salary-trigger
BEFORE UPDATE OF Salary ON Employee
BEGIN

ACTION InformManager (D.Head)
END;
36
IT6405: Database Systems II – Topic 1

Trigger Execution order


1. Execute all BEFORE STATEMENT triggers
2. Disable temporarily all integrity constraints recorded against
the table
3. Loop for each row in the table
– Execute all BEFORE ROW triggers
– Execute the SQL statement against the row and perform
integrity constraint checking of the data
– Execute all AFTER ROW triggers
4. Complete deferred integrity constraint checking against the
table
5. Execute all AFTER STATEMENT triggers

UCSC - 2016 37
IT6405: Database Systems II – Topic 1

Statement Triggers
Monitoring Statement Events
SQL> INSERT INTO Dept (DeptNo, Dname, Loc)
2 VALUES (50, ‘Marketing', ‘Colombo');

Execute only once even if multiple rows affected


BEFORE statement trigger
Dept table
DeptNo Dname Loc
10 Accounting Galle
20 Research Kandy
30 Sales Matara
40 Operations Kegalle
BEFORE row trigger

AFTER row trigger


AFTER statement trigger

UCSC - 2016
Row Triggers
Monitoring Row Events
SQL> UPDATE Emp
2 SET sal = sal * 1.1
3 WHERE deptno = 30;

Execute for each row of the table affected by the event

EMP table BEFORE statement trigger

EMPNO ENAME DEPTNO


BEFORE row trigger
7839 Kapila 30
AFTER row trigger
7698 Bandula 30 BEFORE row trigger
AFTER row trigger
7788 Silva 30 BEFORE row trigger
AFTER row trigger

39
AFTER statement trigger
Example: Registering Operations
SQL> CREATE TRIGGER increase_salary_trg
2 BEFORE UPDATE
3 ON Emp
4 BEGIN
5 INSERT INTO sal_hist (increased, t)
6 VALUES (YES, SYSDATE);
7 END;

Trigger name: increase_salary_trg


Timing: BEFORE executing the statement Can stop code
being wrongly
Triggering event: UPDATE of table
executed more
Target: Emp table than once
Trigger action: INSERT values INTO sal_hist table

UCSC - 2016 40
Example: Calculating Derived
Columns
SQL>CREATE OR REPLACE TRIGGER derive_commission_trg
2 BEFORE UPDATE OF sal ON Emp
3 FOR EACH ROW
4 WHEN (new.job = 'Salesman')
5 BEGIN
6 :new.comm := :old.comm * (:new.sal/:old.sal);
7 END;
Trigger name: derive_commission_trg
Timing: BEFORE executing the statement
Triggering event: UPDATE of sal column
Filtering condition: job = ‘Salesman’
Target: Emp table
Trigger parameters: old, new
Trigger action: calculate the new commission
to be updated

UCSC - 2016 41
IT6405: Database Systems II – Topic 1

Controlling Triggers using SQL


• Disable or Re-enable a database trigger
ALTER TRIGGER trigger_name DISABLE | ENABLE

• Disable or Re-enable all triggers for a table

• Removing a trigger from the database


ALTER TABLE table_name DISABLE | ENABLE ALL TRIGGERS

DROP TRIGGER trigger_name

UCSC - 2016 42
IT6405: Database Systems II – Topic 1

Auditing Table Operations


USER_NAME TABLE_NAME COLUMN_NAME INS UPD DEL
Sunil Emp 1 1 1
Sunil Emp sal 1
Nimal Emp 0 0 0

… continuation
MAX_INS MAX_UPD MAX_DEL
5 5 5
5
5 0 0

UCSC - 2016 43
Example: Counting Statement
Execution
SQL>CREATE OR REPLACE TRIGGER audit_emp
2 AFTER DELETE ON Emp
3 FOR EACH ROW
4 BEGIN
5 UPDATE audit_table SET del = del + 1
6 WHERE user_name = :old.ename
7 AND table_name = 'Emp’;
7 END;

Whenever an employee record is deleted from the database,


the counter in an audit table registering the number of deleted
rows is incremented.

UCSC - 2016 44
Tracing Record
Value Changes
USER_NAME TIMESTAMP ID OLD_LAST_NAME NEW_LAST_NAME
Gihan 12-NOV-97 7950 NULL Dias

Anil 10-DEC-97 7844 Silva Perera

… continuation
OLD_TITLE NEW_TITLE OLD_SALARY NEW_SALARY
NULL Analyst NULL 35000

Clerk Salesman 10000 11000

UCSC - 2016 45
Example: Recording Changes
SQL>CREATE OR REPLACE TRIGGER audit_emp_values
2 AFTER DELETE OR INSERT OR UPDATE ON Emp
3 FOR EACH ROW
4 BEGIN
5 INSERT INTO audit_emp_values (user_name,
6 timestamp, id, old_last_name, new_last_name,
7 old_title, new_title, old_salary, new_salary)
8 VALUES (USER, SYSDATE, :old.empno, :old.ename,
9 :new.ename, :old.job, :new.job,
10 :old.sal, :new.sal);
11 END;

Whenever some details for an employee change, both the previous


and new details are recorded in an audit table to allow tracing the
history of changes.

UCSC - 2016 46
Example: Protecting Referential
Integrity
SQL>CREATE OR REPLACE TRIGGER
cascade_updates
2 AFTER UPDATE OF deptno ON Dept
3 FOR EACH ROW
4 BEGIN
5 UPDATE Emp
6 SET Emp.deptno = :new.deptno
7 WHERE Emp.deptno = :old.deptno;
8 END
Whenever the department number changes, all employee records
for this department will automatically be changed as well, so that
the employees will continue to work for the same department.

UCSC - 2016 47

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy