0% found this document useful (0 votes)
19 views

Tutorial 11 Part2.Constraint Trigger

The document discusses constraints and triggers in a database management system. It defines constraints as relationships among data elements that must be enforced by the DBMS, including primary keys, foreign keys, and various attribute- and tuple-based constraints. Triggers allow users to specify that certain actions should occur automatically when a triggering event, such as an insert, update or delete statement, takes place. Triggers contain an event, condition, and action, and can be defined at either the row or statement level.

Uploaded by

Vlad Voznitsa
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)
19 views

Tutorial 11 Part2.Constraint Trigger

The document discusses constraints and triggers in a database management system. It defines constraints as relationships among data elements that must be enforced by the DBMS, including primary keys, foreign keys, and various attribute- and tuple-based constraints. Triggers allow users to specify that certain actions should occur automatically when a triggering event, such as an insert, update or delete statement, takes place. Triggers contain an event, condition, and action, and can be defined at either the row or statement level.

Uploaded by

Vlad Voznitsa
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/ 31

Constraints and Triggers

1
Constraints

 Constraint is a relationship among data


elements that the DBMS is required to
enforce.
 Types of Constraint:
 Primary key
 Foreign key
 Attribute-based constraints
 Tuple-based constraints
 Assertions
2
Enforcing Foreign-Key
Constraints -1
Beers(name, manf)
Sells(bar, beer, price)
 If there is a foreign-key constraint from
attributes of relation R (e.g. Sells) to a key of
relation S (e.g. Beers), 2 violations are possible:
1. An insert or update to R (e.g. Sells)
introduces values not found in S (e.g. Beers).
 Example: An insert or update to Sells that
introduces a nonexistent beer
 Must be rejected
3
Enforcing Foreign-Key
Constraints -2

2. A deletion or update to S (e.g. Beers)


causes some tuples of R (e.g. Sells) to
dangle
 Example: A deletion or update to Beers that
removes a beer value found in some tuples
of Sells
 Can be handled in 3 ways:
1. Default : Reject the modification
2. Cascade : Make the same changes in Sells
 E.g.: Delete the “Bud” tuple from Beers and
then delete all tuples from Sells that have
beer = “Bud”
4
Enforcing Foreign-Key
Constraints -3
3. Set NULL : Change the beer to NULL
 E.g.: Delete the “Bud” tuple from Beers and
change all tuples of Sells that have beer = “Bud”
to have beer = NULL

5
Choosing a Policy

 We may choose policies SET NULL or CASCADE by


using:
ON [UPDATE, DELETE][SET NULL CASCADE]
 Otherwise, the default (Reject) is used

6
Example
CREATE TABLE Sells (
bar CHAR(20),
beer CHAR(20),
price REAL,
FOREIGN KEY(beer)
REFERENCES Beers(name)
ON DELETE SET NULL
ON UPDATE CASCADE
);
7
Attribute-Based Checks

 Attribute-based checks are constraints on the value


of a particular attribute
 Are checked only when a value for that
attribute is inserted or updated

CREATE TABLE Sells (


bar CHAR(20),
beer CHAR(20) CHECK ( beer IN
(SELECT name FROM Beers)),
price REAL CHECK ( price <= 5.00 )
); 8
Tuple-Based Checks

 Constraint is added as a relation-schema


element
 The condition may refer to any attribute of the
current relation
 Checked on insert or update only

9
Example

 Only Mary‟s Bar can sell beer for more than $5:
CREATE TABLE Sells (
bar CHAR(20),
beer CHAR(20),
price REAL,
CHECK (bar = “Mary’s Bar” OR
price <= 5.00)
);

10
Assertions
 Assertions are database-schema elements, like
relations or views.
CREATE ASSERTION <name>
CHECK ( <condition> );
 Condition may refer to any relation or attribute in the
database schema
 In principle, assertions are checked after every
modification to any relation of the database

11
Example

 In Sells(bar, beer, price), no bar may charge an


average of more than $5.

CREATE ASSERTION NoRipOffBars CHECK (


NOT EXISTS (
SELECT bar FROM Sells
GROUP BY bar
HAVING AVG(price) > 5.0
));

12
Exercise

 Consider the following database schema


 supplier(supplier#, sname, rating, city)

 parts(part#, pname, color, weight)

 projects(project#, pjname, city)

 spj(supplier#, part#, project#, qty)

 Express the constraint: “No project can use more


than 100 units of part P65 ” in SQL

13
Solution

 spj(supplier#, part#, project#, qty)


 No project can use more than 100 units of part P65

CREATE ASSERTION parts-constraint CHECK


(NOT EXISTS (SELECT project#, SUM(qty)
FROM spj
WHERE part#=„P65‟
GROUP BY project#
HAVING SUM(qty)>100))

14
Triggers: Motivation

 Assertions are powerful, but the DBMS


often can‟t tell when they need to be
checked
 Attribute- and tuple-based checks are
checked at known times, but are not
powerful
 Triggers let the user decide when to check
for a powerful condition
15
Event-Condition-Action Rules
 Trigger is also called event-condition-action
(ECA) rule
 Event
 Is a type of database modification that fires the
trigger
 Condition
 Is the condition to perform the action
 Can be any SQL boolean-valued expression
 Action
 Can be any SQL statements

16
Preliminary Example
 Write a trigger so that, whenever there is
an insertion into Sells(bar, beer, price) with
unknown beers, add that beer name to
Beers table, with manufacturer set to
NULL.

17
Example
CREATE TRIGGER BeerTrigger The event
AFTER INSERT ON Sells
REFERENCING NEW ROW AS NewTuple
FOR EACH ROW
The condition
WHEN (NewTuple.beer NOT IN
(SELECT name FROM Beers))
INSERT INTO Beers(name)
The action
VALUES(NewTuple.beer);

18
Options: CREATE TRIGGER
 CREATE TRIGGER <name>
 Option:

CREATE OR REPLACE TRIGGER <name>


 Useful if there is a trigger with that name and you
want to modify the trigger

19
Options: The Event

 AFTER INSERT ON <Attribute>


 AFTER can be BEFORE

 Example: BEFORE INSERT ON Sells

 INSERT can be DELETE or UPDATE.

 And UPDATE can be UPDATE … OF … for a


particular attribute
 Example: AFTER UPDATE OF price ON Sells

20
Options: REFERENCING
AFTER INSERT ON Sells
REFERENCING NEW ROW AS NewTuple
 INSERT statements imply a new row or new table
(i.e., a set of inserted tuples)
 DELETE implies an old row or old table

 UPDATE implies both

[NEW OLD][ROW TABLE] AS <name>

21
Options: FOR EACH ROW

 FOR EACH ROW indicates row-level;


Its absence indicates statement-level
 Row Level Triggers:
 Execute once for each modified tuple

 Statement-Level Triggers:
 Execute once for an SQL statement,
regardless of how many tuples are modified

22
Options: The Condition

 Any boolean-valued condition is


appropriate
 It is evaluated before or after the triggering
event, depending on whether BEFORE or
AFTER is used in the event

23
Options: The Action
 There can be one or more SQL statement in
the action
 Surround by BEGIN . . . END if there is more than
one

24
Example
 Sells(bar, beer, price)
 RipOffBars(bar)
 Write a trigger so that any bar that raises the
price of any beer by more than $1 will be
inserted into RipOffBars relation

25
The Trigger The event –
When there is
change
CREATE TRIGGER PriceTrigger to the price
AFTER UPDATE OF price ON Sells
REFERENCING Since it’s Updates, we have
OLD ROW AS oldRow old and new tuples
NEW ROW AS newRow Condition:
We need to consider a raise in
FOR EACH ROW each price change price > $1
WHEN(newRow.price > oldRow.price + 1.00)
INSERT INTO RipOffBars When the price change
VALUES(newRow.bar); is great enough, add
the bar to RipoffBars
26
Exercise
 Given the following relational schema:
 Employee(ID, name, address, position)

 CompanyStats(numEmployee, numProduct,
revenue)
 Create two triggers that will result in the automatic
tracking of the number of employees a company
manages.

27
Solution - 1
 The first trigger increments the number of employees each time a
new person is hired

CREATE TRIGGER Employee_Hired


AFTER INSERT ON Employee
FOR EACH ROW
UPDATE CompanyStats
SET numEmployee = numEmployee + 1

 Each time a new row is inserted into Employee table,


numEmployee in CompanyStats table will be incremented by 1

28
Solution - 2
 The second trigger decrements the number of employees each
time an employee leaves the company

CREATE TRIGGER Employee_Leaves


AFTER DELETE ON Employee
FOR EACH ROW
UPDATE CompanyStats
SET numEmployee = numEmployee - 1

 Each time a row is deleted from Employee table, numEmployee


in CompanyStats table will be decremented by 1

29
Exercise
 We have a Student table that contains the student
ID (SID), the GPA of student, etc.
 For each new student with GPA > 4.0, he/she will be
automatically be enrolled in the honor seminar
course (CS123)
 The Enroll table is defined as:
 Enroll (SID, courseNumber)
 Write a trigger to automatically enroll the student in
honor seminar

30
Solution
CREATE TRIGGER HonorSeminarEnrollment
AFTER INSERT ON Student
REFERENCING NEW ROW AS newStudent
FOR EACH ROW
WHEN (newStudent.GPA > 4.0)
Insert Into Enroll
Values (newStudent.SID, „CS123‟);

31

You might also like