Presentation is loading. Please wait.

Presentation is loading. Please wait.

Constraints and Triggers

Similar presentations


Presentation on theme: "Constraints and Triggers"— Presentation transcript:

1 Constraints and Triggers

2 What’s IC? Integrity Constraints define the valid states of SQL-data by constraining the values in the base tables. Restrictions on allowable data in DB In addition to structure and type restrictions imposed by the schema definition

3 Why IC? To catch data-entry errors
As correctness criteria when writing DB updates To enforce consistency across data in DB To tell the system about the data -- it may choose to store the data or process queries accordingly

4 How to Enforce IC? Declaration of IC
As parts of schema definition DBMS checks all DB modifications to see whether an IC is violated. If yes, reject the operation, or do some compensating operations

5 Different Kinds of IC Table constraint Domain constraint Assertions
Unique constraint Referential constraint Table check constraint Domain constraint Assertions

6 Review: Key Constraints
Two ways to declare keys: PRIMARY KEY UNIQUE

7 Declaring PK Column-level CREATE TABLE Student (
sno char(10) PRIMARY KEY, name varchar(20), age integer, dept char(8) );

8 Declaring PK (cont.) Table-level CREATE TABLE SC ( sno char(10),
cno char(20), grade integer, PRIMARY KEY (sno, cno) ); Essential if PK is more than one attribute

9 Declaring UNIQUE Column-level Table-level CREATE TABLE Student (
sno char(10) UNIQUE, name char(20) UNIQUE, … ); Table-level CREATE TABLE SC ( sno char(10), cno char(20), ... UNIQUE (sno, cno) );

10 Enforcing Key Constraints
Checked only when an insertion or update occurs. An index on key attributes is vital for efficient checking. Otherwise, a table scan is needed.

11 Referential Integrity
Data must make sense across DB, not just in a table. Source of problem: relationship Example: A tuple (‘007’,’CS123’,88) in SC makes sense only when there is a student ‘007’ in Student and a course ‘CS123’ in Course. But not vice versa.

12 Foreign Keys In relation R, if its attribute A references the key (PK or UNIQUE) K of another relation S, then A is a foreign key of R. Example SC.sno Student.sno referencing attr. referenced attr.

13 Referential Integrity Rule
Any value appearing in FK of R must also appear in the referenced K of S. Note FK may have NULL values in R R and S may be the same relation eg. S(sno, name, age, dept, monitorSno)

14 Declaring RI Column-level CREATE TABLE SC (
sno char(10) REFERENCES Student(sno), cno char(20) REFERENCES Course(cno), grade integer );

15 Declaring RI (cont.) Table-level
CREATE TABLE SC ( sno char(10), cno char(20), grade integer, FOREIGN KEY (sno) REFERENCES Student(sno), FOREIGN KEY (cno) REFERENCES Course(cno), ); Essential if FK is more than one attribute

16 RI Violations Four kinds of modifications may violate RI constraint:
1. insert into R(FK) with nonexistent FK values 2. update R(FK) with nonexistent FK values 3. delete from S(K) referenced K values 4. update S(K) on referenced K values S(K,...) R(FK,...)

17 Enforcing RI Default policy: handling 1,2,3,4
reject violating modifications Cascade policy: handling 3,4 delete/update K  delete/update FK Set-Null policy: handling 3,4 delete/update K  set NULL to FK Set-Default policy: handling 3,4 delete/update K  set default to FK

18 Example “Correct” policy is a design decision. CREATE TABLE SC (
sno char(10) REFERENCES Student(sno) ON DELETE SET NULL ON UPDATE CASCADE, ...... ); “Correct” policy is a design decision.

19 Order of Modifications
Example Insertion of a new course into Course must be done before any student can take it. But what order for circular constraints ? A is a FK referencing B, and B is a FK referencing A

20 Deferring the Checking
Any IC may be declared NOT DEFERRABLE (default): checked immediately DEFERRABLE: immediate or deferred checking Deferred: checked at the end of the current transaction, just before commit. Initial constraint mode for deferrable IC: i.e., at the start of SQL-transaction INITIALLY DEFERRED INITIALLY IMMEDIATE May be changed later: SET CONSTRAINT constraint_name DEFERRED | IMMEDIATE; Naming constraints covered later.

21 Example CREATE TABLE Univ( name CHAR(30) PRIMARY KEY,
address VARCHAR(255), presCert# INT UNIQUE REFERENCES Academician(cert#) DEFERRABLE INITIALLY DEFERRED );

22 Not-Null Constraints Restrict attributes to disallow NULL values
To enforce not-null constraints, disallow: update to NULL insertion without providing values set-null policy

23 Example CREATE TABLE S ( sno char(10) PRIMARY KEY,
name char(20) NOT NULL, age integer, dept varchar(30) NOT NULL ); Sometimes NOT NULL is default, declare NULL if allowing NULL values.

24 Attribute-based CHECK
Constraints on values for an attribute Domain integrity Declaration CHECK (condition) condition can be anything that could follow WHERE Satisfied iff condition is not false for any row of a table condition can refer to other attributes/relations, but only in the FROM of a subquery

25 Example CREATE TABLE Student ( sno char(10) PRIMARY KEY,
name varchar(20), age integer CHECK (age > 0), dept char(20) CHECK (dept NOT IN (SELECT name FROM departments WHERE location=‘MinHang’)) );

26 Enforcement Condition is checked only when the associated attribute changes due to INSERT or UPDATE. Reject the modification if it violates the constraints. Condition can become FALSE due to changes of other attributes/relations. eg. Update department X’s location to ‘MinHang’. This is invisible to the CHECK.

27 Tuple-based CHECK Constraints on values for tuples in a relation
Table-level CHECK Involving multiple attributes Form: like attribute-based check, but condition can refer to any attribute of the relation. Or to other relations/attributes in subqueries

28 Example CREATE TABLE Student ( sno char(10) PRIMARY KEY,
name varchar(20), age integer, dept char(20), CHECK (dept IN (‘CS’,’MA’,’EE’) OR age<16) );

29 Enforcement Checked whenever a tuple is INSERTed or UPDATEed in the relation. An attribute-based CHECK can also be written as a table-based CHECK. Which is preferable? If violated, reject the operation. Invisible to other relations.

30 Modification of Constraints
Naming constraints CONSTRAINT name constraint-definition Examples 1. sno char(10) CONSTRAINT pksno PRIMARY KEY 2. age integer CONSTRAINT chkage CHECK (age > 0)

31 Altering Constraints on Tables
Syntax ALTER TABLE tablename DROP CONSTRAINT cname | ADD CONSTRAINT cname cons-def Can only add tuple-based constraints: tuple-based CHECK, PK, FK Must hold for the current relation instance

32 Assertions Constraints on entire relation or entire DB Declaration
CREATE ASSERTION assertion_name CHECK (condition); Condition must be true when the assertion is created and must remain true. Checked whenever a mentioned relation changes.

33 Example Checked whenever SC changes.
CREATE ASSERTION sumlimit CHECK (500 <= ALL (SELECT SUM(grade) FROM SC GROUP BY sno)); Checked whenever SC changes. Tuple-based check also can do this? No. Check would not be made on deletion of a tuple from SC.

34 Droping Assertions Syntax DROP ASSERTION assertion_name;

35 Triggers ECA rules: event-condition-action rules
Event = changes in DB, e.g., “insertion into S” Condition = a test for whether or not the trigger applies Action = one or more SQL statements

36 Triggers vs. Constraints
triggering who event cond actions specify Constraint violation check reject system Trigger explicitly action explicitly programmer specified cond. specified

37 Declaration CREATE TRIGGER name BEFORE UPDATE [OF A1,A2,...]
AFTER INSERT ON R DELETE REFERENCING {OLD ROW | OLD TABLE} AS oldvar , {NEW ROW | NEW TABLE} AS newvar FOR EACH {ROW | STATEMENT} WHEN(condition) actions

38 Events INSERT ON R DELETE ON R UPDATE ON R UPDATE OF A1,...,An ON R
These operations may cause a trigger on R activated.

39 Action Condition Actions are taken only if the condition is satisfied.
Activating a trigger does not mean that actions will sure be taken. WHEN (condition) may be omitted: unconditional actions.

40 Actions A sequence of SQL statements. BEGIN ... END

41 Row-level or Statement-level
FOR EACH ROW = row-level trigger execute once for each modified tuple FOR EACH STATEMENT or Omitted= statement-level trigger execute once for the statement

42 Referencing Clause Give names to OLD / OLD TABLE / NEW / NEW TABLE, which refer to tuples / tables been changed. DELETE: OLD = deleted tuples INSERT: NEW = inserted tuples UPDATE: OLD = before update NEW = after update

43 Example CREATE TRIGGER beststudent AFTER INSERT ON SC
REFERENCING NEW ROW AS newSC FOR EACH ROW WHEN (newSC.grade = 100) SELECT name, dept FROM S WHERE S.sno = newSC.sno;

44 Example CREATE TRIGGER casc AFTER DELETE ON S
REFERENCING OLD ROW AS oldS FOR EACH ROW WHEN (0 < (SELECT COUNT(*) FROM SC WHERE SC.sno = oldS.sno)) DELETE FROM SC WHERE SC.sno = oldS.sno;

45 End


Download ppt "Constraints and Triggers"

Similar presentations


Ads by Google