Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 Constraints and Triggers in SQL. 2 Constraints are conditions that must hold on all valid relation instances SQL2 provides a variety of techniques for.

Similar presentations


Presentation on theme: "1 Constraints and Triggers in SQL. 2 Constraints are conditions that must hold on all valid relation instances SQL2 provides a variety of techniques for."— Presentation transcript:

1 1 Constraints and Triggers in SQL

2 2 Constraints are conditions that must hold on all valid relation instances SQL2 provides a variety of techniques for expressing integrity constraints as part of the database schema –key integrity constraints –referential integrity constraints –domain constraints –assertions Triggers –Not in SQL2, but in SQL3 –A sort of stored procedure –Already supported in many commercial systems

3 3 Declaring Keys Two ways to declare keys: PRIMARY KEY or UNIQUE –A table may have any number of UNIQUE declarations but only one primary key Two ways to declare a primary key in the CREATE TABLE statement –create table MovieStar ( name char(30) PRIMARY KEY, address varchar(255), gender char(1), birthdate date ); –create table MovieStar ( name char(30), address varchar(255), gender char(1), birthdate date, PRIMARY KEY(name) // when a composite key );

4 4 Uniqueness Another way to declare key is to use the keyword UNIQUE –create table MovieStar ( name char(30) PRIMARY KEY, address varchar(255) UNIQUE, gender char(1), birthdate date, UNIQUE(birthdate) ); Index creation on key attributes –CREATE UNIQUE INDEX yearIndex on movie(year); The constraint must be checked every time we try to change the database –here, on insertion and on update

5 5 Primary Key vs. Uniqueness A foreign key can only reference the primary key of a relation Implementers sometimes put some meaning on primary key beyond SQL2 –Usually create an index on primary key attributes –Sometimes cluster the relation on its primary key

6 6 Declaring Foreign-Key Constraints Two ways to declare a foreign key –REFERENCES ( –FOREIGN KEY REFERENCES ( ) –Studio(name, address, presC#) MovieExec(name, address, cert#, netWorth) –Create table Studio ( name char(30) primary key, address varchar(255), presC# int REFERENCES MovieExec(cert#)); –Create table Studio ( name char(30) primary key, address varchar(255), presC# int, FOREIGN KEY presC# REFERENCES MovieExec(cert#));

7 7 Maintaining Referential Integrity How to maintain referential constraints –The default policy: reject violating modifications –Cascade policy –Set-null policy Declare them with ON DELETE or ON UPDATE followed by SET NULL or CASCADE –Create table Studio ( name char(30) primary key, address varchar(255), presC# int references MovieExec(cert#) on delete set null on update cascade ); –Note, those are the delete and update on MovieExec(cert#)

8 8 Constraints on the Values of Attributes Not-null constraints –Disallow tuples in which this attribute is NULL –table Studio required presC# not to NULL, –create table Studio ( name char(30) primary key, address varchar(255), presC# int references MovieExec(cert#) not null );

9 9 Attribute-based CHECK Constraints Keyword CHEK, followed by a parenthesized condition that must hold for every value of the attribute –The condition can be anything that could follow WHERE in SQL –create table Studio ( name char(30) primary key, address varchar(255), presC# int references MovieExec(cert#) CHECK (presC# >= 100000) // To require that certificate numbers be at least six digits ); –gender char(1) check (gender in (‘F’, ‘M’)), // Only ‘F’ and ‘M’ are allowed as value

10 10 Limitation on CHECK Constraints Other attribute or other relation can be mentioned in the condition However, checking constraints is associated with the attribute in question only ! An erroneous example –Studio(name, address, presC#) MovieExec(name, address, cert#, netWorth) –In the create statement for Studio, consider the below: presC# int check (presC# in (select cert# from MovieExec)) –This does not model referential constraints correctly! (WHY)

11 11 Domain Constraints Can also constrain the values of an attribute by declaring a domain –SQL2 provides the special keyword VALUE to refer to a value in the domain Examples –Create domain GenderDomain char(1) check (VALUE in (‘F’, ‘M’)); // To allow ‘F’ and ‘M’ as values gender GenderDomain, –Create domain CertDomain int check (VALUE >= 100000); // To enforce six-digit certificates for the attribute presC# presC# CertDomain references MovieExec(cert#),

12 12 Global Constraints Two categories –tuple-based CHECK constraint, which restrict any aspect of the tuples of a single relation –assertions, which are constraints that may involve entire relations or several tuple-variables ranging over the same relation

13 13 Tuple-based CHECK Constraints Keyword CHECK + a parenthesized condition Check every time a tuple is inserted into R and every time a tuple R is updated The condition can be anything that could appear in a WHERE clause –However, tuple-based CHECK is invisible to other relations. So, tuple- based checks can be violated sometimes Example –Create table MovieStar ( name char(30) unique, address varchar(255), gender char(1), birthdate date, CHECK (gender = ‘F’ OR name not like ‘Ms.%’) );

14 14 Assertions SQL2’s assertions (general constraints) allow us to enforce any condition Assertions are themselves schema elements Format CREATE ASSERTION CHECK ( ); ssertion must be always true, and any modification that makes false will be rejected

15 15 Assertion vs. Tuple-based CHECK (1) –MovieExec(name, address, cert#, netWorth) Studio(name, address, presC#) –No one can become the president of a studio unless their net worth is at least $10,000,000 –CREATE ASSERTION RichPres CHECK// Assertion (not exists (select * from Studio, MovieExec where presC# = cert# AND netWorth < 10,000,000 ) ); –Create table Studio (// Tuple-based CHECK name char(30) primary key, address varchar(255), presC# int references MoiveExec(cert#), check (presC# not in (select cert# from MovieExec where netWorth < 10,000,000) )); –The second does not check modification on MovieExec table

16 16 Assertion vs. Tuple-based CHECK (2) –Movie(title, year, length, inColor,studioName, producerC#) –The total length of all movies by a given studio shall not exceed 10,000 minutes Assertion –Create assertion SumLength check (10000 >= all (select sum(length) from Movie group by studioName)); Tuple-based CHECK constraint –check (10000 >= all (select sum(length) from Movie group by studioName)); –The check would not be made on deletion of a tuple from Movie

17 17 Comparison of Constraints

18 18 Giving Names to Constraints In order to modify or delete an existing constraint, it is necessary that the constraint have a name –Precede the constraint by keyword CONSTRAINT and a constraint name Examples –name char(30) constraint NameIsKey primary key, –gender char(1) constraint NoAndro check (gender in (‘F’, ‘M’)), –create domain CertDomain int constraint SixDigits check (value >= 100000); –CONSTRAINT RightTitle CHECK (gender = ‘F’ or name not like ‘Ms.%’)

19 19 Altering Constraints on Tables Can modify the set of constraints associated with domain, an attribute or a table with an ALTER statement –use DROP or ADD keyword Examples –ALTER TABLE MovieStar DROP CONSTRAINT NameIsKey; –ALTER TABLE MovieStar DROP CONSTRAINT NoAndro; –ALTER TABLE MovieStar DROP CONSTRAINT RightTitle; –ALTER TABLE MovieStar ADD CONSTRAINT NameIsKey primary key (name); –ALTER TABLE MovieStar ADD CONSTRAINT NoAndro check (gender in (‘F’, ‘M’));

20 20 Altering Domain Constraints and Assertions Drop and add constraints on a domain in essentially the same way that we drop and add tuple-based checks –ALTER DOMAIN CertDomain DROP CONSTRAINT SixDigits; –ALTER DOMAIN CertDomain ADD CONSTRAINT SixDigits check (value >= 100000); To delete an assertion –DROP ASSERTION RichPres;

21 21 Triggers in SQL3 Triggers (event-condition-action rules or ECA rules) allow us to explicitly specify triggering events as well as actions to be taken based on condition result –Triggers are only tested when certain events (insert, delete, update, etc), specified by the database programmer, occur –A trigger tests a condition. If the condition does not hold, then nothing happens –If the condition is satisfied, the action associated with the trigger is performed by the DBMS –The action could be any sequence of database operations Most commercial systems support the trigger, but not an assertion !

22 22 SQL3 Trigger Features Action can be executed before, after, or instead of the triggering event Action can refer to both old and new values of tuples that were inserted, deleted, or updated in the event that triggered the action Update events may specify a particular column or set of columns A condition may be specified by a WHEN clause, and the action is only executed if the rule is triggered and the condition holds Programmer has an option in which the action is performed either: –Once for each modified tuple row-level trigger FOR EACH ROW –Once for all the tuples that are changed in one database operation statement-level trigger

23 23 Triggers Example (1/2) –MovieExec(name, address, cert#, netWorth) To restore any attempt to lower the net worth of movie executives –CREATE TRIGGER NetWorthTrigger AFTER UPDATE of netWorth on MovieExec// Event REFERENCING OLD AS OldTuple, NEW AS NewTuple WHEN (OldTuple.netWorth > NewTuple.netWorth)// Condition update MovieExec // Action set netWorth = OldTuple.netWorth where cert# = NewTuple.cert# FOR EACH ROW

24 24 Example of Triggers (2/2) –MovieExec(name, address, cert#, netWorth) To prevent the average net worth of movie executives from dropping below $500,000. –// An trigger for the update event CREATE TRIGGER AvgNetWorthTrigger INSTEAD OF UPDATE OF netWorth ON MovieExec REFERENCING OLD_TABLE AS OldStuff, NEW_TABLE AS NewStuff WHEN (500000 <= (select avg(netWorth) // evaluated after modification from ((MovieExec except OldStuff) union NewStuff))) delete from MovieExec where (name, address, cert#, netWorth) in OldStuff; insert into MovieExec (select * from NewStuff);

25 25 Assertions in SQL3 SQL3 also extends SQL2 assertions in two important ways –assertions are triggered by programmer-specific events, rather than by events that the system decides might violate the constraint –optionally, the assertion may refer to each tuple of a table, like a tuple- level check, rather than to the table or tables as a whole The major difference is that the assertion makes it explicit when the check needs to be performed The SQL3 assertion easier for the system implementors, but harder for the user

26 26 Example of SQL3 Assertions require that no one can become the president of a studio unless their net worth is at least $10,000,000 –CREATE ASSERTION RichPres AFTER INSERT ON Studio, UPDATE OF presC# on studio, UPDATE OF netWorth on MovieExec, INSERT ON MovieExec CHECK (not exists (select * from Studio, MovieExec where presC# = cert# and netWorth < 10000000 )


Download ppt "1 Constraints and Triggers in SQL. 2 Constraints are conditions that must hold on all valid relation instances SQL2 provides a variety of techniques for."

Similar presentations


Ads by Google