0% found this document useful (0 votes)
72 views25 pages

Lecon Database

This document discusses database triggers. It defines triggers as user-defined stored programs that are automatically executed in response to certain events on a particular table or view. The document outlines the key components of a trigger as the event, condition, and action. It provides examples of different types of triggers and discusses their invocation at the statement level versus row level. The timing of triggers as before or after events is also covered. The document explores potential applications of triggers and discusses concepts like cascading triggers.

Uploaded by

Jef Dira
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)
72 views25 pages

Lecon Database

This document discusses database triggers. It defines triggers as user-defined stored programs that are automatically executed in response to certain events on a particular table or view. The document outlines the key components of a trigger as the event, condition, and action. It provides examples of different types of triggers and discusses their invocation at the statement level versus row level. The timing of triggers as before or after events is also covered. The document explores potential applications of triggers and discusses concepts like cascading triggers.

Uploaded by

Jef Dira
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/ 25

CSE 480

Database Systems

Database Triggers

1
Introduction

• CON ST RAIN T S: Constraints are general restric-


tions on the data in the database.
• Three Important Components
1. Event: Execution of insert, delete and update
function on a table.
2. Condition: Restrictions on the data in the database
defined by the database system or user-procedure.
3. Action: When the Condition is satisfied, certain
action is taken by the database system or by user-
procedure.
• When an event occurs, condition is checked and if
the condition is true the action is executed.

2
Built-in Constraints, Assertions and
Triggers

• BU ILT IN CON ST RAIN T : Both the condition


and the action are system defined and is created
at the time the table is created using CREAT E
T ABLE command.
Example:
CREATE TABLE Student(
Sid NUMBER (5) CONSTRAINT
PK_Student PRIMARY KEY,
Sname VARCHAR2 (30),
----
---- );
• ASSERT ION : Here the condition is user defined
(not built-in) and the action is system defined.
Example: A student must take at least two courses:
CREATE ASSERTION EnrollmentControl
CHECK (Not Exists( Select count(*)
From StudentCourse
Group by sno
Having count(cno)>2))
3
Assertion is invoked as a result of insert, delete or
update events. CHECK provides the condition
and when the condition is true violation occurs and
the action is taken by the system which is to prevent
the event from taking place.
• T RIGGERS: User defines the condition and the
action.
Example: Enter the inserted student record into the
table LansingStudents if the inserted student’s ad-
dress is East Lansing.

CREATE TRIGGER InsertStudent


AFTER INSERT ON Student
FOR EACH ROW
WHEN (NEW.Saddr="East Lansing")
BEGIN
INSERT INTO
LansingStudents(Sid, Sname, Saddr, Sdno)
Values
(NEW.Sid, NEW.Sname, NEW.Saddr, NEW.Sdno)
END

4
Various Proposals
• IBM’s Starburst (research prototype), SQL-3 stan-
dard, Oracle Triggers, DB2 triggers, Sql-Server.
• Triggers: Implicitly executed as a result of insert,
delete and update transactions on a base table. Both
condition and action are user defined.
• Statement level invocation, row level invocation.

5
Potential Applications
• Allow automatic notification of conditions
(e.g., Student’s average grade falling below a thresh-
old)
• Automatic maintenance of derived attributes.
• Maintain currency of materialized views.
• Maintaining mirrored (replicated) databases
• Many others

6
Oracle Triggers
• Basic Structure
– Event:
(Triggering Statement)
– Condition:
(Trigger Restriction)
– Action:
(Trigger Action)
• Example:

Table:
Inventory(Part_no, parts_on_hand, reorder_point)
CREATE OR REPLACE TRIGGER REORDER
AFTER UPDATE ON Inventory
FOR EACH ROW
WHEN(new.parts_on_hand <new.reorder_point)
BEGIN
ORDER PARTS
END
Event: UPDATE ON Inventory, Condition: When
clause, Action: ORDER PARTS (this can be an
SQL statement, a stored procedure, etc.).

7
12 Possible Combinations for Triggers
• Three Characteristics:
1. Action (Event): INSERT, DELETE
and UPDATE SQL statement
2. Level: Statement level, Row level
3. Timing: BEFORE, AFTER
• 3*2*2=12 possible combinations.
• Same table can have a combination
of these triggers defined.

8
Statement Level Versus Row Level
• Two major differences:
1. How often Trigger fires (invoca-
tions):
– Statement level: Trigger fires once per SQL
statement
– Row level: Trigger fires once for each row af-
fected by the SQL statement.
2. Visibility
– Statement level: no accesses to column values
currently being updated.
– Row level: has access to column values cur-
rently being updated.

9
Examples
• Trigger invocations (statement level):
If total salary exceeds $100000000.00 print a message.
– A statement level trigger:
CREATE OR REPLACE TRIGGER MaxTotalSal
AFTER INSERT OR UPDATE ON Employee
Begin
IF 100000000<(select SUM(EmpSal)
FROM Employee)
Print "Total Salary Exceeds $100000000.00)
END
– Give 10% raise to all employees
SQL: UPDATE Employee SET EmpSal=1.1 *
EmpSal
– Above SQL will fire the trigger MaxTotalSalary
only once.

10
Examples cont’d
• Trigger invocations (row level):
A row If new salary> $1000000.00 print a message.
– A row level trigger:
CREATE OR REPLACE TRIGGER MaxSal
AFTER INSERT OR UPDATE ON Employee
FOR EACH ROW
WHEN (NEW.EmpSal>1000000)
BEGIN
Print "Employee Salary exceeds $1000000.00)
END
– Give 10% raise to all employees
SQL: UPDATE Employee SET
EmpSal=1.1 * EmpSal
– trigger invoked N times if N tuples in Employee
affected.

11
Examples cont’d (visibility)
• Check 50% increase in salary for individual employ-
ees

CREATE OR REPLACE TRIGGER MaxSal


AFTER INSERT OR UPDATE ON Employee
FOR EACH ROW
WHEN (NEW.EmpSal-OLD.EmpSal>1.5*OLD.EmpSal)
BEGIN
Print "Employee Salary increased by 50%)
END

• Detect individual salary increases through NEW.EmpSalary


and OLD.EmpSalary
• Statement level trigger does not have access to vari-
ables NEW.EmpSalary and OLD.EmpSalary.

12
Timing
• BEFORE: ACT ION is before the event.
• AFTER: ACT ION is after the event.
• Both BEFORE and AFTER Row level trigger have
access to OLD and NEW
• Check 50% increase in salary could use BEFORE.
• BEFORE has the opportunity to override the new
salary.

13
Column-Name-Clause
Column name clause places tight restrictions on the fir-
ing specification. It fires only when the specified columns
are affected by the event statements.
example:
CREATE OR REPLACE TRIGGER MaxSal
AFTER UPDATE OF EmpSal ON Employee
FOR EACH ROW
WHEN (NEW.EmpSal-OLD.EmpSal>1.5*OLD.EmpSal)
BEGIN
Print "Employee Salary increased by 50%)
END

14
More Examples
• Maintain a table GoodStudents which has students
with grade in a course 4.0. Also indicate the number
of rows inserted in each SQL statement.
Trigger1:

CREATE OR REPLACE TRIGGER GoodStudents


AFTER INSERT OR UPDATE OF Grade ON StudentCourse
FOR EACH ROW
WHEN (NEW.Grade=4.0)
BEGIN
Insert into GoodStudentsTable
(NEW.sid, NEW.cno)
Count=Count+1
END

Trigger2:

CREATE TRIGGER InitializeCount


BEFORE UPDATE ON StudentCourse
BEGIN
SET Count=0
END

15
Increase the grades of all students in course c1 by .5

UPDATE StudentCourse
SET Grade=Grade+.5
WHERE cno="c1" AND Grade!=4.0

StudentCourse
sid cno grade
s1 c1 3.5
s2 c1 4.0
s3 c1 3.5
s4 c1 3.0
s1 c2 3.5
s5 c2 4.0

• Trigger 1 is a row level trigger and will be invoked 2


times.
• Trigger 2 is a statement level trigger and will be in-
voked only once.

16
Need a WHEN Clause?
1. WHEN (boolean expression) clause can include any
PL/SQL boolean expression.
2. The logic of the boolean test can be moved to the
body (action) of the trigger.

17
Firing Sequence of Multiple Triggers
1. Execute BEFORE statement Trigger
2. LOOP for each ROW affected by SQL statement
(a) Execute BEFORE ROW Trigger
(b) Lock and change ROW
(c) Perform Constraints Checking
(The lock is not released until the transaction is
committed)
(d) Execute AFTER ROW Trigger.
3. Execute AFTER statement trigger.

Note that Constraints have higher run before the triggers.

18
Firing Within DELETE CASCADE
1. As each parent is deleted, all children related to the
parent are deleted. When child is deleted it’s state-
ment and row level triggers are fired.
2. Example:
Delete from Department Where Dno in (’d1’, ’d2’)

Department BEFORE statement


Department BEFORE ROW
delete Department tuple ’d1’
Student BEFORE statement
Student BEFORE ROW
Delete Student tuple 1
Student AFTER ROW
Student BEFORE ROW
Delete Student tuple 2
- - -
Student AFTER statement
Department BEFORE ROW
- - -
Department AFTER ROW
Department AFTER statement

19
Cascading of Triggers
The execution of the action part of a trigger may cause
the activation of other triggers.
Cascading can be recursive or nested.
1. Recursive trigger:
When an application updates table T1, which fires
trigger TR1 updating table T1. This is a direct re-
cursion. Recursion can be indirect as well where an
application updates table T1, which fires trigger TR1
updating table T2. Trigger TR2 defined on table T2
then updates table T1.
2. Nested triggers:
If a trigger changes a table on which there is another
trigger, the second trigger is then activated and can
then call a third trigger, and so on.
Maximum number of cascading is 32 in Oracle;
When it exceeds 32, all database changes as a result
of original SQL are rolled back.
Example:
CREATE TRIGGER SalaryControl
AFTER INSERT, DELETE, UPDATE ON Salary OF EMP
WHEN (Select AVG(Salary) From EMP>100)
20
THEN Update EMP
Set Salary=.9*Salary
Example: Table EMP
Employee Salary
john 90
David 100
Insert tuple (Rick 200)
How many times the trigger is invoked?

21
Applications (using oracle triggers)
1. Derived data Maintenance:
Computed Attributes: Attribute value is computed
on the fly such as the attribute AverageGrade.
Materialized Views: Physical up-to-date copy of the
view is maintained by the system. Challenge is to
keep the physical copy updated as soon as the base
tables are updated.
2. Database Replication: Mirrored databases (multiple
copies of the same database) are maintained at var-
ious locations so that copies are physically close to
where it is used to improve response time. Challenge
is to keep all these copies in sync.
3. Workflow Management: Organize the working activ-
ities within an enterprise. Monitor the assignment of
tasks and their coordination.

22
Materialized Views
Maintaining materialized Views:
Done through
• Refresh approach: Recomputing from scratch after
each update to base table.
• Incremental approach: Requires computing the posi-
tive and the negative deltas, consisting of tuples that
should be, respectively, inserted into or deleted from
the views.
Example:
Define view GoodStudents(Sname)
SELECT DISTINCT Sname
FROM Student, StudentCourse
WHERE Sno=sno
GROUP BY sno
HAVING AVG(Grade)>3.0
Events causing recomputation of the view:
Insert, delete, update(Grade) in StudentCourse.

23
Refresh:
CREATE TRIGGER RefreshGS1
AFTER INSERT, DELETE, UPDATE(Grade) on
StudentCourse
DELETE * FROM GoodStudent
INSERT INTO GoodStudent(Sname)
(SELECT DISTINCT Sname
FROM Student, StudentCourse
WHERE Sno=sno
GROUP BY sno
HAVING AVG(Grade)>3.0

24
Incremental (more complex):
CREATE TRIGGER IncrementalGS1
AFTER INSERT, DELETE, UPDATE StudentCourse
FOR EACH ROW
INSERT INTO GoodStudents(Sname)
SELECT DISTINCT Sname
FROM Student
WHERE new.sno=Sno and 3.0<(Select AVG(Grade)
from StudentCourse X
where new.sno=X.sno)
CREATE TRIGGER IncrementalGS2
AFTER INSERT, DELETE, UPDATE StudentCourse
FOR EACH ROW
DELETE FROM GoodStudents X
WHERE X.Sname=
(Select Sname
FROM Student
WHERE old.sno=Sno and 3.0>(Select AVG(Grade)
From StudentCourse Y
where Old.sno=Y.sno)

25

You might also like