Constraints and Triggers. What’s IC? Integrity Constraints define the valid states of SQL-data by constraining the values in the base tables. –Restrictions.

Slides:



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

Relational Database. Relational database: a set of relations Relation: made up of 2 parts: − Schema : specifies the name of relations, plus name and type.
Database Management Systems, R. Ramakrishnan and J. Gehrke1 The Relational Model Chapter 3.
The Relational Model. Introduction Introduced by Ted Codd at IBM Research in 1970 The relational model represents data in the form of table. Main concept.
SQL Lecture 10 Inst: Haya Sammaneh. Example Instance of Students Relation  Cardinality = 3, degree = 5, all rows distinct.
Fall 2005 ICS184/EECS116 – Notes 08 1 ICS 184/EECS116: Introduction to Data Management Lecture Note 8 SQL: Structured Query Language -- DDL.
Chapter 7 Notes on Foreign Keys Local and Global Constraints Triggers.
SQL Constraints and Triggers
The Relational Model Class 2 Book Chapter 3 Relational Data Model Relational Query Language (DDL + DML) Integrity Constraints (IC) (From ER to Relational)
Cs3431 Constraints Sections 6.1 – 6.5. cs3431 Example CREATE TABLE Student ( sNum int, sName varchar (20), prof int, CONSTRAINT pk PRIMARY KEY (snum),
CMPT 354, Simon Fraser University, Fall 2008, Martin Ester 28 Database Systems I The Relational Data Model.
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.
Constraints We have discussed three types of integrity constraints: primary keys, not null constraints, and unique constraints. CREATE TABLE Movies ( title.
SPRING 2004CENG 3521 The Relational Model Chapter 3.
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.
1 Relational Model. 2 Relational Database: Definitions  Relational database: a set of relations  Relation: made up of 2 parts: – Instance : a table,
The Relational Model Lecture 3 Book Chapter 3 Relational Data Model Relational Query Language (DDL + DML) Integrity Constraints (IC) From ER to Relational.
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.)
Fall 2001Arthur Keller – CS 1809–1 Schedule Today Oct. 23 (T) Constraints. u Read Sections Assignment 4 due. Project Part 3 due Oct. 24 (W). Oct.
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.
The Relational Model These slides are based on the slides of your text book.
Relational Data Model, R. Ramakrishnan and J. Gehrke with Dr. Eick’s additions 1 The Relational Model Chapter 3.
SCUHolliday - coen 1789–1 Schedule Today: u Constraints, assertions, triggers u Read Sections , 7.4. Next u Triggers, PL/SQL, embedded SQL, JDBC.
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.
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)
1 The Relational Model. 2 Why Study the Relational Model? v Most widely used model. – Vendors: IBM, Informix, Microsoft, Oracle, Sybase, etc. v “Legacy.
FALL 2004CENG 351 File Structures and Data Management1 Relational Model Chapter 3.
SQL: DDL John Ortiz Cs.utsa.edu.
ICS 321 Fall 2011 Constraints, Triggers, Views & Indexes Asst. Prof. Lipyeow Lim Information & Computer Science Department University of Hawaii at Manoa.
Constraints, Triggers and Views COMSATS INSTITUTE OF INFORMATION TECHNOLOGY, VEHARI.
SQL Integrity Constraints. 421B: Database Systems - Integrity Constraints 2 Integrity Constraints (Review) q An IC describes conditions that every legal.
IST 210 Constraints and Triggers. IST Constraints and Triggers Constraint: relationship among data elements DBMS should enforce the constraints.
Advanced SQL: Triggers & Assertions
Dec 8, 2003Murali Mani Constraints B term 2004: lecture 15.
7 1 Constraints & Triggers Chapter Constraints and triggers? Constraints: Certain properties that the DBMS is required to enforce –E.g. primary.
Advanced SQL Concepts - Checking of Constraints CIS 4301 Lecture Notes Lecture /6/2006.
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 
1 SQL: Structured Query Language Chapter 5 (cont.)  Constraints  Triggers.
CS34311 The Relational Model. cs34312 Why Relational Model? Currently the most widely used Vendors: Oracle, Microsoft, IBM Older models still used IBM’s.
Database Management COP4540, SCS, FIU Database Trigger.
Constraints and Views Chap. 3-5 continued (7 th ed. 5-7)
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.
1 Introduction to Database Systems, CS420 SQL Constraints.
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke1 The Relational Model Chapter 3.
1 CS122A: Introduction to Data Management Lecture #4 (E-R  Relational Translation) Instructor: Chen Li.
CENG 351 File Structures and Data Management1 Relational Model Chapter 3.
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.
Chapter 6: Integrity (and Security)
Constraints and Triggers
Foreign Keys Local and Global Constraints Triggers
Database Construction (and Usage)
SQL: Constraints and Triggers
CPSC-310 Database Systems
The Relational Model Relational Data Model
CMSC-461 Database Management Systems
SQL – Constraints & Triggers
CPSC-608 Database Systems
-Transactions in SQL -Constraints and Triggers
Presentation transcript:

Constraints and Triggers

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

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

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

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

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

Declaring PK Column-level CREATE TABLE Student ( sno char(10) PRIMARY KEY, name varchar(20), age integer, dept char(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

Declaring UNIQUE Column-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) );

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.

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.

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.

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)

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

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

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,...)

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

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

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

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.

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

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

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.

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

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’)) );

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.

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

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) );

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.

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)

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

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.

Example 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.

Droping Assertions Syntax DROP ASSERTION assertion_name;

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

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

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

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.

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.

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

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

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

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;

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;

End