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.

Slides:



Advertisements
Similar presentations
1 Constraints, Triggers and Active Databases Chapter 9.
Advertisements

Database Modifications CIS 4301 Lecture Notes Lecture /30/2006.
Chapter 7 Notes on Foreign Keys Local and Global Constraints Triggers.
M.P. Johnson, DBMS, Stern/NYU, Sp20041 C : Database Management Systems Lecture #13 Matthew P. Johnson Stern School of Business, NYU Spring, 2004.
SQL Constraints and Triggers
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5 More SQL: Complex Queries, Triggers, Views, and Schema Modification.
Database Modifications, Data Types, Views. Database Modifications A modification command does not return a result as a query does, but it changes the.
Cs3431 Constraints Sections 6.1 – 6.5. cs3431 Example CREATE TABLE Student ( sNum int, sName varchar (20), prof int, CONSTRAINT pk PRIMARY KEY (snum),
Constraints and Triggers Foreign Keys Local and Global Constraints Triggers.
Triggers The different types of integrity constraints discussed so far provide a declarative mechanism to associate “simple” conditions with a table such.
CMSC424: Database Design Instructor: Amol Deshpande
Introduction to Structured Query Language (SQL)
Winter 2002Arthur Keller – CS 1809–1 Schedule Today: Jan. 31 (TH) u Constraints. u Read Sections , Project Part 3 due. Feb. 5 (T) u Triggers,
CPSC-608 Database Systems Fall 2011 Instructor: Jianer Chen Office: HRBB 315C Phone: Notes #4.
Database Modifications A modification command does not return a result as a query does, but it changes the database in some way. There are three kinds.
SQL Keys and Constraints Justin Maksim. Key Declaration Key constraint defined within the CREATE TABLE command Key can be declared using either the PRIMARY.
1 SQL: Structured Query Language (‘Sequel’) Chapter 5 (cont.)
Introduction to Structured Query Language (SQL)
Triggers.
CMPT 354, Simon Fraser University, Fall 2008, Martin Ester 157 Database Systems I SQL Constraints and Triggers.
Chapter 7 Constraints and Triggers Spring 2011 Instructor: Hassan Khosravi.
SQL: Constraints and Triggers Chapter 6 Ullman and Widom Certain properties we’d like our database to hold Modification of the database may break these.
SQL Constraints & Triggers May 10 th, Agenda Big picture –what are constraints & triggers? –where do they appear? –why are they important? In SQL.
Chapter 6: Integrity and Security Thomas Nikl 19 October, 2004 CS157B.
SCUHolliday - coen 1789–1 Schedule Today: u Constraints, assertions, triggers u Read Sections , 7.4. Next u Triggers, PL/SQL, embedded SQL, JDBC.
Lecture 7 Integrity & Veracity UFCE8K-15-M: Data Management.
Constraints on Relations Foreign Keys Local and Global Constraints Triggers Following lecture slides are modified from Jeff Ullman’s slides
Ad Hoc Constraints Objectives of the Lecture : To consider Ad Hoc Constraints in principle; To consider Ad Hoc Constraints in SQL; To consider other aspects.
Winter 2006Keller, Ullman, Cushing9–1 Constraints Commercial relational systems allow much more “fine-tuning” of constraints than do the modeling languages.
CS411 Database Systems Kazuhiro Minami 06: SQL. Constraints & Triggers Foreign Keys Local and Global Constraints Triggers.
CpSc 462/662: Database Management Systems (DBMS) (TEXNH Approach) Constraints, Triggers and Index James Wang.
Introduction to Indexes. Indexes An index on an attribute A of a relation is a data structure that makes it efficient to find those tuples that have a.
1 ICS 184: Introduction to Data Management Lecture Note 11: Assertions, Triggers, and Index.
Database Management COP4540, SCS, FIU Constraints and security in SQL (Ch. 8.6, Ch22.2)
7 1 Chapter 7 Introduction to Structured Query Language (SQL) Database Systems: Design, Implementation, and Management, Seventh Edition, Rob and Coronel.
ICS 321 Fall 2011 Constraints, Triggers, Views & Indexes Asst. Prof. Lipyeow Lim Information & Computer Science Department University of Hawaii at Manoa.
IST 210 Constraints and Triggers. IST Constraints and Triggers Constraint: relationship among data elements DBMS should enforce the constraints.
Fall 2001Database Systems1 Triggers Assertions –Assertions describe rules that should hold for a given database. –An assertion is checked anytime a table.
Advanced SQL: Triggers & Assertions
Dec 8, 2003Murali Mani Constraints B term 2004: lecture 15.
Chapter 9 Constraints. Chapter Objectives  Explain the purpose of constraints in a table  Distinguish among PRIMARY KEY, FOREIGN KEY, UNIQUE, CHECK,
Oracle 11g: SQL Chapter 4 Constraints.
7 1 Constraints & Triggers Chapter Constraints and triggers? Constraints: Certain properties that the DBMS is required to enforce –E.g. primary.
1 Chapter 6 Constraints uForeign Keys uConstraints.
Chapter 4 Constraints Oracle 10g: SQL. Oracle 10g: SQL 2 Objectives Explain the purpose of constraints in a table Distinguish among PRIMARY KEY, FOREIGN.
Constraints and Triggers. What’s IC? Integrity Constraints define the valid states of SQL-data by constraining the values in the base tables. –Restrictions.
Referential Integrity checks, Triggers and Assertions Examples from Chapter 7 of Database Systems: the Complete Book Garcia-Molina, Ullman, & Widom.
Advanced SQL Concepts - Checking of Constraints CIS 4301 Lecture Notes Lecture /6/2006.
© D. Wong Normalization  Purpose: process to eliminate redundancy in relations due to functional or multi-valued dependencies.  Decompose relation.
Different Constraint Types Type Where Declared When activated Guaranteed to hold? Attribute with attribute on insertion not if CHECK or update subquery.
1 CSCE Database Systems Anxiao (Andrew) Jiang The Database Language SQL.
Assertions and triggers1. 2 Constraints Attribute-based CHECK constraints create table … ( postcode number(4) check (postcode > 0) ); Checked at update.
DATA AND SCHEMA MODIFICATIONS CHAPTERS 4,5 (6/E) CHAPTER 8 (5/E) 1.
Chapter 5 : Integrity And Security  Domain Constraints  Referential Integrity  Security  Triggers  Authorization  Authorization in SQL  Views 
Session 1 Module 1: Introduction to Data Integrity
Constraining Attribute Values Constrain invalid values –NOT NULL –gender CHAR(1) CHECK (gender IN (‘F’, ‘M’)) –MovieName CHAR(30) CHECK (MovieName IN (SELECT.
Database Management COP4540, SCS, FIU Database Trigger.
The Relational Model of Data Prof. Yin-Fu Huang CSIE, NYUST Chapter 2.
SCUHolliday - coen 1789–1 Schedule Today: u Constraints, assertions, triggers u Read Sections , 7.4. Next u Embedded SQL, JDBC. u Read Sections.
Murali Mani Constraints. Murali Mani Keys: Primary keys and unique CREATE TABLE Student ( sNum int, sName varchar (20), dept char (2), CONSTRAINT key.
More SQL: Complex Queries, Triggers, Views, and Schema Modification
Constraints and Triggers
Foreign Keys Local and Global Constraints Triggers
Introduction to Structured Query Language (SQL)
SQL: Constraints and Triggers
2018, Fall Pusan National University Ki-Joune Li
CMSC-461 Database Management Systems
SQL – Constraints & Triggers
CPSC-608 Database Systems
Assertions and Triggers
Presentation transcript:

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 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 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 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 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 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 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 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 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# >= ) // 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 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 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 >= ); // To enforce six-digit certificates for the attribute presC# presC# CertDomain references MovieExec(cert#),

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 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 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 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 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 Comparison of Constraints

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 >= ); –CONSTRAINT RightTitle CHECK (gender = ‘F’ or name not like ‘Ms.%’)

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 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 >= ); To delete an assertion –DROP ASSERTION RichPres;

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 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 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 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 ( <= (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 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 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 < )