Professional Documents
Culture Documents
SQL: Constraints and Triggers: Chapter 5, 5.7-5.8
SQL: Constraints and Triggers: Chapter 5, 5.7-5.8
Chapter 5, 5.7-5.8
Inserts/deletes/updates that violate ICs are disallowed. Can be used to ensure application semantics (e.g., sid is a key), or prevent inconsistencies (e.g., sname has to be a string, age must be < 200)
Types of ICs: Domain constraints, primary key constraints, foreign key constraints, general constraints.
Syntax: CHECK conditional-expression. The conditional expression captures more general ICs than keys. The conditional expressions can use queries. The conditional expressions required to hold only if the associated table is nonempty. A CHECK constraint may be expressed over several tables; however, it is often expressed over one single table. Constraints can be named:
CONSTRAINT MyConstraint CHECK conditional-expression
The assertion is not associated with any one of the tables involved. ASSERTION is the right solution; not associated with either table.
7
Write SQL integrity constraints (domain, key, foreign key, or CHECK constraints; or assertions) for given requirements:
Students must have a minimum cgpa of 5. Every TA must also be a student. The total percentage of all assignments to projects for a given student must be at most 100%. A TA must have a cgpa higher than any student that she coaches.
FROM Students)) =0 )
9
WHERE S.sid=W.sid AND W.pid=P.pid AND P.ta=TA.sid AND S.cgpa > TA.cgpa) =0)
11
Triggers
Trigger: procedure that starts automatically if specified changes occur to the DBMS Three parts:
Event (activates the trigger) Condition (tests whether the triggers should run) Action (what happens if the trigger runs)
12
Triggers
BEFORE trigger: action executed before the activating event occurs. AFTER trigger: action executed after the activating event occurs. INSTEAD trigger: action executed instead of the activating event. Row-level trigger: executed once per modified row (that satisfies the trigger condition). Statement-level trigger: executed once per modifying statement. Transition variables: NEW, OLD, NEW TABLE, OLD TABLE.
13
Illustrates use of NEW TABLE to refer to a set of newly inserted tuples Exists since SQL:1999
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke 15
Summary
SQL allows specification of rich integrity constraints Triggers respond to changes in the database
17