constraints and triggers - concordia...
TRANSCRIPT
2
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
3
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
4
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”
5
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
6
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
7
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
);
8
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 ) );
9
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
10
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)
);
11
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
12
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
));
13
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
14
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))
15
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
16
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
17
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.
18
Example
CREATE TRIGGER BeerTrigger
AFTER INSERT ON Sells
REFERENCING NEW ROW AS NewTuple
FOR EACH ROW
WHEN (NewTuple.beer NOT IN
(SELECT name FROM Beers))
INSERT INTO Beers(name)
VALUES(NewTuple.beer);
The event
The condition
The action
19
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
20
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
21
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>
22
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
23
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
24
Options: The Action
There can be one or more SQL statement in
the action
Surround by BEGIN . . . END if there is more than
one
25
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
26
The Trigger
CREATE TRIGGER PriceTrigger
AFTER UPDATE OF price ON Sells
REFERENCING
OLD ROW AS oldRow
NEW ROW AS newRow
FOR EACH ROW
WHEN(newRow.price > oldRow.price + 1.00)
INSERT INTO RipOffBars
VALUES(newRow.bar);
The event – When there is change to the price
Since it’s Updates, we have old and new tuples
We need to consider each price change
Condition: a raise in price > $1
When the price change is great enough, add the bar to RipoffBars
27
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.
28
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
29
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
30
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