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.

Slides:



Advertisements
Similar presentations
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5 More SQL: Complex Queries, Triggers, Views, and Schema Modification.
Advertisements

1 Constraints, Triggers and Active Databases Chapter 9.
Relational Database. Relational database: a set of relations Relation: made up of 2 parts: − Schema : specifies the name of relations, plus name and type.
SQL Lecture 10 Inst: Haya Sammaneh. Example Instance of Students Relation  Cardinality = 3, degree = 5, all rows distinct.
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
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.
Maintaining Referential Integrity Pertemuan 2 Matakuliah: T0413/Current Popular IT II Tahun: 2007.
End of SQL: Triggers, Impedance Mismatch and Transactions February 6 th, 2004.
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,
Remaining Topics in SQL to be covered… NULL values in SQL Outer joins in SQL Constraints and Triggers in SQL Embedded SQL.
CPSC-608 Database Systems Fall 2011 Instructor: Jianer Chen Office: HRBB 315C Phone: Notes #4.
Lecture #4 October 19, 2000 SQL. Administration Exam date officially moved to December 7 th, 6:30pm, here. Homework #3 – will be on the web site tomorrow.
SQL Keys and Constraints Justin Maksim. Key Declaration Key constraint defined within the CREATE TABLE command Key can be declared using either the PRIMARY.
Remaining Topics in SQL to be covered… NULL values in SQL Outer joins in SQL Constraints and Triggers in SQL Embedded SQL.
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.
Chapter 6: Integrity Objective Key Constraints (Chapter 2) Cardinality Constraints (Chapter 2) Domain Constraints Referential Integrity Assertions Triggers.
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 #19 May 13 th, Agenda Trip Report End of constraints: triggers. Systems aspects of SQL – read chapter 8 in the book. Going under the lid!
Constraints on Relations Foreign Keys Local and Global Constraints Triggers Following lecture slides are modified from Jeff Ullman’s slides
Winter 2006Keller, Ullman, Cushing9–1 Constraints Commercial relational systems allow much more “fine-tuning” of constraints than do the modeling languages.
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)
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.
Dec 8, 2003Murali Mani Constraints B term 2004: lecture 15.
Constraints cis 407 Types of Constraints & Naming Key Constraints Unique Constraints Check Constraints Default Constraints Misc Rules and Defaults Triggers.
Chapter 9 Constraints. Chapter Objectives  Explain the purpose of constraints in a table  Distinguish among PRIMARY KEY, FOREIGN KEY, UNIQUE, CHECK,
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.
Different Constraint Types Type Where Declared When activated Guaranteed to hold? Attribute with attribute on insertion not if CHECK or update subquery.
Deductive Databases General idea: some relations are stored (extensional), others are defined by datalog queries (intensional). Many research projects.
1 CSCE Database Systems Anxiao (Andrew) Jiang The Database Language SQL.
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.
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.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 4 Basic SQL تنبيه : شرائح العرض (Slides) هي وسيلة لتوضيح الدرس واداة.
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.
More SQL: Complex Queries, Triggers, Views, and Schema Modification
Fundamental of Database Systems
Constraints and Triggers
Foreign Keys Local and Global Constraints Triggers
Introduction to Database Systems, CS420
CPSC-608 Database Systems
Remaining Topics in SQL to be covered…
SQL: Constraints and Triggers
CPSC-310 Database Systems
2018, Fall Pusan National University Ki-Joune Li
More SQL: Complex Queries, Triggers, Views, and Schema Modification
CMSC-461 Database Management Systems
SQL – Constraints & Triggers
CPSC-608 Database Systems
-Transactions in SQL -Constraints and Triggers
Assertions and Triggers
Presentation transcript:

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 properties Build handlers into the database definition

Keys: Fundamental Constraint In the CREATE TABLE statement, use: –PRIMARY KEY, UNIQUE CREATE TABLE MovieStar ( name CHAR(30) PRIMARY KEY, address VARCHAR(255), gender CHAR(1)); Or, list at end of CREATE TABLE PRIMARY KEY (name)

Keys... Can use the UNIQUE keyword in same way –…but for any number of attributes –foreign keys, which reference attributes of a second relation, only reference PRIMARY KEY Indexing Keys CREATE UNIQUE INDEX YearIndex ON Movie(year) Makes insertions easier to check for key constraints

Referential Integrity Constraints 2 rules for Foreign Keys: Movies(MovieName, year) ActedIn(ActorName, MovieName) 1) Foreign Key must be a reference to a valid value in the referenced table. 2) … must be a PRIMARY KEY in the referenced table.

Declaring FK Constraints FOREIGN KEY REFERENCES ( ) CREATE TABLE ActedIn ( Name CHAR(30) PRIMARY KEY, MovieName CHAR(30) REFERENCES Movies(MovieName)); Or, summarize at end of CREATE TABLE FOREIGN KEY MovieName REFERENCES Movies(MovieName) MovieName must be a PRIMARY KEY

How to Maintain? Given a change to DB, there are several possible violations: –Insert new tuple with bogus foreign key value –Update a tuple to a bogus foreign key value –Delete a tuple in the referenced table with the referenced foreign key value –Update a tuple in the referenced table that changes the referenced foreign key value

How to Maintain? Recall, ActedIn has FK MovieName... Movies(MovieName, year) (Fatal Attraction, 1987) ActedIn(ActorName, MovieName) (Michael Douglas, Fatal Attraction) insert: (Rick Moranis, Strange Brew)

How to Maintain? Policies for handling the change… –Reject the update (default) –Cascade (example: cascading deletes) –Set NULL Can set update and delete actions independently in CREATE TABLE MovieName CHAR(30) REFERENCES Movies(MovieName)) ON DELETE SET NULL ON UPDATE CASCADE

Constraining Attribute Values Constrain invalid values –NOT NULL –gender CHAR(1) CHECK (gender IN (‘F’, ‘M’)) –MovieName CHAR(30) CHECK (MovieName IN (SELECT MovieName FROM Movies)) Last one not the same as REFERENCE –The check is invisible to the Movies table!

Constraining Values with User Defined ‘Types’ Can define new domains to use as the attribute type... CREATE DOMAIN GenderDomain CHAR(1) CHECK (VALUE IN (‘F’, ‘M’)); Then update our attribute definition... gender GenderDomain

More Complex Constraints... …Among several attributes in one table –Specify at the end of CREATE TABLE CHECK (gender = ‘F’ OR name NOT LIKE ‘Ms.%’)

Declaring Assertions CREATE ASSERTION CHECK ( ) CREATE ASSERTION RichPres CHECK (NOT EXISTS (SELECT * FROM Studio, MovieExec WHERE presC# = cert# AND netWorth < ))

Different Constraint Types Type Where Declared When activated Guaranteed to hold? Attribute with attribute on insertion not if CHECK or update subquery Tuple relation schema insertion or not if CHECK update to subquery relation Assertion database schema on change to Yes any relation mentioned

Giving Names to Constraints Why give names? In order to be able to alter constraints. Add the keyword CONSTRAINT and then a name: ssn CHAR(50) CONSTRAINT ssnIsKey PRIMARY KEY CREATE DOMAIN ssnDomain INT CONSTRAINT ninedigits CHECK (VALUE >= AND VALUE <= CONSTRAINT rightage CHECK (age >= 0 OR status = “dead”)

Altering Constraints ALTER TABLE Product DROP CONSTRAINT positivePrice ALTER TABLE Product ADD CONSTRAINT positivePrice CHECK (price >= 0) ALTER DOMAIN ssn ADD CONSTRAINT no-leading-1s CHECK (value >= ) DROP ASSERTION assert1.

Triggers Enable the database programmer to specify: when to check a constraint, what exactly to do. A trigger has 3 parts: An event (e.g., update to an attribute) A condition (e.g., a query to check) An action (deletion, update, insertion) When the event happens, the system will check the constraint, and if satisfied, will perform the action. NOTE: triggers may cause cascading effects. Database vendors did not wait for standards with triggers!

Elements of Triggers (in SQL3) Timing of action execution: before, after or instead of triggering event The action can refer to both the old and new state of the database. Update events may specify a particular column or set of columns. A condition is specified with a WHEN clause. The action can be performed either for once for every tuple, or once for all the tuples that are changed by the database operation.

Example: Row Level Trigger CREATE TRIGGER NoLowerPrices AFTER UPDATE OF price ON Product REFERENCING OLD AS OldTuple NEW AS NewTuple WHEN (OldTuple.price > NewTuple.price) UPDATE Product SET price = OldTuple.price WHERE name = NewTuple.name FOR EACH ROW

Statement Level Trigger CREATE TRIGGER average-price-preserve INSTEAD OF UPDATE OF price ON Product REFERENCING OLD_TABLE AS OldStuff NEW_TABLE AS NewStuff WHEN (1000 < (SELECT AVG (price) FROM ((Product EXCEPT OldStuff) UNION NewStuff)) DELETE FROM Product WHERE (name, price, company) IN OldStuff; INSERT INTO Product (SELECT * FROM NewStuff)

Bad Things Can Happen CREATE TRIGGER Bad-trigger AFTER UPDATE OF price IN Product REFERENCING OLD AS OldTuple NEW AS NewTuple WHEN (NewTuple.price > 50) UPDATE Product SET price = NewTuple.price * 2 WHERE name = NewTuple.name FOR EACH ROW