Presentation is loading. Please wait.

Presentation is loading. Please wait.

SQL – Constraints & Triggers

Similar presentations


Presentation on theme: "SQL – Constraints & Triggers"— Presentation transcript:

1 SQL – Constraints & Triggers
CS4433 Database Systems SQL – Constraints & Triggers

2 Constraints and Triggers
A constraint is a relationship among data elements that the DBMS is required to enforce Example: key constraints Triggers are only executed when a specified condition occurs, e.g., insertion of a tuple. Easier to implement than many constraints

3 Kinds of Constraints Keys Foreign-key, or referential-integrity
Value-based constraints Constrain values of a particular attribute Tuple-based constraints Relationship among components Assertions: any SQL Boolean expression

4 Foreign Keys Consider Relation Movie(title, year, length, inColor, studioName, prodC#) We might expect that a studioName value is a real studio --- something appearing in Studio.name A constraint that requires a studioName in Movie to be some key in Studio is called a foreign-key constraint Expression: use the keyword REFERENCES, either: Within the declaration of an attribute, when only one attribute is involved. As an element of the schema, as: FOREIGN KEY ( <list of attributes> ) REFERENCES <relation> ( <attributes> ) Referenced attributes must be declared PRIMARY KEY or UNIQUE

5 Example: With Attribute
CREATE TABLE Movie ( Title char(50), year int , length int, studioName int, prodC# int, PRIMARY KEY (title, year), FOREIGN KEY (studioName) REFERENCES Studio) ) CREATE TABLE Studio ( name CHAR(20), adress varchar, presC# int REFERENCES MovieExec(cert#) ); Another way for this presC# int, FOREIGN KEY (presC# )REFERENCES MovieExec(cert#));

6 Enforcing Foreign-Key Constraints
If there is a foreign-key constraint from attributes of relation R to the primary key of relation S, two violations are possible: An insertion or update to R introduces values not found in S A deletion or update to S causes some tuples of R to “dangle” R S

7 Actions Taken Suppose R = Movie, S = Studio
An insert or update to Movie that introduces a nonexistent Studio must be rejected A deletion or update to Studio that removes a studio value found in some tuples of Movie can be handled in three ways Default : Reject the modification Cascade : Make the same changes in Movie Deleted studio: delete Movie tuple Updated studio: change value in Movie. NULL : Change the studioname in Movie to NULL

8 Choosing a Policy When we declare a foreign key, we may choose policies SET NULL or CASCADE independently for deletions and updates Follow the foreign-key declaration by: ON [UPDATE, DELETE][SET NULL CASCADE] Otherwise, the default (reject) is used CREATE TABLE Movie ( Title char(50), year int , length int, studioName int, prodC# int, PRIMARY KEY (title, year), FOREIGN KEY (studioName) REFERENCES Studio) ON DELETE SET NULL ON UPDATE CASCADE);

9 Checks Attribute-based Check
Put a constraint on the value of a particular attribute Ensure that attribute values satisfy specified condition CHECK( <condition> ) must be added to the declaration for the attribute The condition may use the name of the attribute, but any other relation or attribute name must be in a subquery CREATE TABLE Movie ( Title char(50), year int CHECK ( year <= 2030) length int, studioName int CHECK (studioName IN (select name from Studio)), prodC# int, )

10 How is Check different from Foreign Key?
The kind of conditions to enforce? The timing/actions of enforcing? An attribute-based check is checked only when a value for that attribute is inserted or updated Example: CHECK (year <= 2030) checks every new year and rejects it if it is more than 2030. Example: CHECK (studioName IN (SELECT name FROM Studio)) not checked if a studio is deleted from Studio (unlike foreign-keys)

11 Tuple-Based Checks CHECK ( <condition> ) may be added as another element of a schema definition The condition may refer to any attribute of the relation, but any other attributes or relations require a subquery Checked on insert or update only Example: only length of the Movie” Long Movie” can be more than 180 mins: CREATE TABLE Movie ( Title char(50), studioName int CHECK (studio name IN (select name from Studio)), prodC# int, year int CHECK ( year <= 2030) length int, CHECK (title = ’Long Movie’ OR length <= 180) );

12 Not null Constraint For certain attributes null values may be inappropriate Prohibit the insertion of a null value for the attribute Any other modification that would cause a null to be inserted in an attribute declared to ne nut null generates error message Student name: There can not be unknown student Declare it as; Name varchar(20) not null

13 Assertions CREATE ASSERTION <name> CHECK ( <condition> );
These are database-schema elements, like relations or views An assertion is a statement in SQL that ensures a certain condition will always exist in the database. Assertions are like column and table constraints, except that they are specified separately from table definitions.  Defined by: CREATE ASSERTION <name> CHECK ( <condition> ); Condition may refer to any relation or attribute in the database schema

14 Example create assertion recent_licenses
check ( ( select count(*) from nurses where license_renewal_date < ' ' ) = 0 )

15 Another Example In Drinkers(name, addr, phone) and Bars(name, addr, license), there cannot be more bars than drinkers. CREATE ASSERTION FewBar CHECK ( (SELECT COUNT(*) FROM Bars) <= (SELECT COUNT(*) FROM Drinkers) );

16 Timing of Assertion Checks
In principle, we must check every assertion after every modification to any relation of the database A clever system can observe that only certain changes could cause a given assertion to be violated Example: No change to Beers can affect FewBar. Neither can an insertion to Drinkers

17 Triggers Motivation Attribute- and tuple-based checks have limited capabilities Assertions are sufficiently general for most constraint applications, but they are hard to implement efficiently The DBMS must have real intelligence to avoid checking assertions that couldn’t possibly have been violated Solution: Trigger a procedure that starts automatically if specified changes occur to the DBMS A trigger allows the user to specify when the check occurs Like an assertion, a trigger has a general-purpose condition and also can perform any sequence of SQL database modifications

18 Event-Condition-Action Rules
Another name for “trigger” is ECA rule, or event-condition-action rule Event : (activates the trigger) typically a type of database modification, e.g., “insert on Sells.” Condition : (tests whether the trigger should run) Any SQL Boolean-valued expression Action : (procedure executed when trigger runs) Any SQL statements Example: Instead of using a foreign-key constraint and rejecting insertions into Sells(bar, beer, price) with unknown beers, a trigger can add that beer to Beers, with a NULL manufacturer

19 Example: Trigger The event CREATE TRIGGER youngStudentUpdate
AFTER INSERT ON Student REFERENCING NEW TABLE NewStudent FOR EACH STATEMENT INSERT INTO YoungStudent(snum, sname, major, standing, age) SELECT snum, sname, major, standing, age FROM NewStudent N WHERE N.age <= 18; apply once per statement The action

20 Example: Trigger Definition
The event CREATE TRIGGER BeerTrig 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 condition The action

21 Options: The Event AFTER can be BEFORE
Also, INSTEAD OF, if the relation is a view A great way to execute view modifications: have triggers translate them to appropriate modifications on the base tables INSERT can be DELETE or UPDATE And UPDATE can be UPDATE ON a particular attribute


Download ppt "SQL – Constraints & Triggers"

Similar presentations


Ads by Google