M.P. Johnson, DBMS, Stern/NYU, Sp20041 C20.0046: Database Management Systems Lecture #13 Matthew P. Johnson Stern School of Business, NYU Spring, 2004.

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.
CSE 544 Constraints Lecture #3 Friday, January 13, 2011 Dan Suciu , Winter
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.
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.
1 Introduction to Database Systems CSE 444 Lecture 05: Views, Constraints April 9, 2008.
M.P. Johnson, DBMS, Stern/NYU, Spring C : Database Management Systems Lecture #12 M.P. Johnson Stern School of Business, NYU Spring, 2008.
1 Data Definition in SQL So far we have see the Data Manipulation Language, DML Next: Data Definition Language (DDL) Data types: Defines the types. Data.
1 Lecture 06: SQL Friday, January 14, Outline Indexes Defining Views (6.7) Constraints (Chapter 7) We begin E/R diagrams (Chapter 2)
M.P. Johnson, DBMS, Stern/NYU, Spring C : Database Management Systems Lecture #14 M.P. Johnson Stern School of Business, NYU Spring, 2005.
SPRING 2004CENG 3521 The Relational Model Chapter 3.
1 Lecture 05: SQL Wednesday, October 8, Outline Outer joins (6.3.8) Database Modifications (6.5) Defining Relation Schema in SQL (6.6) Indexes.
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.
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.
M.P. Johnson, DBMS, Stern/NYU, Spring C : Database Management Systems Lecture #15 M.P. Johnson Stern School of Business, NYU Spring, 2005.
Correlated Queries SELECT title FROM Movie AS Old WHERE year < ANY (SELECT year FROM Movie WHERE title = Old.title); Movie (title, year, director, length)
CMPT 354, Simon Fraser University, Fall 2008, Martin Ester 157 Database Systems I SQL Constraints and Triggers.
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.
Exercises Product ( pname, price, category, maker) Purchase (buyer, seller, store, product) Company (cname, stock price, country) Person( per-name, phone.
SQL Constraints & Triggers May 10 th, Agenda Big picture –what are constraints & triggers? –where do they appear? –why are they important? In SQL.
SQL (almost end) April 26 th, Agenda HAVING clause Views Modifying views Reusing views.
The Relational Model These slides are based on the slides of your text book.
The Relational Model. Review Why use a DBMS? OS provides RAM and disk.
1 Lecture 6: Views Friday, January 17th, Updating Views How can I insert a tuple into a table that doesn’t exist? Employee(ssn, name, department,
1 SQL Constraints and Programming. 2 Agenda Constraints in SQL Systems aspects of SQL.
1 ICS 184: Introduction to Data Management Lecture Note 11: Assertions, Triggers, and Index.
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.
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.
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.
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.
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.
CS34311 The Relational Model. cs34312 Why Relational Model? Currently the most widely used Vendors: Oracle, Microsoft, IBM Older models still used IBM’s.
Constraining Attribute Values Constrain invalid values –NOT NULL –gender CHAR(1) CHECK (gender IN (‘F’, ‘M’)) –MovieName CHAR(30) CHECK (MovieName IN (SELECT.
1 Lecture 5: Outerjoins, Schema Creation and Views Wednesday, January 15th, 2003.
Aggregation SELECT Sum(price) FROM Product WHERE manufacturer=“Toyota” SQL supports several aggregation operations: SUM, MIN, MAX, AVG, COUNT Except COUNT,
1 Lecture 06 Data Modeling: E/R Diagrams Wednesday, January 18, 2006.
Constraints and Views Chap. 3-5 continued (7 th ed. 5-7)
1 Lecture 05: SQL Wednesday, October 8, Outline Database Modifications (6.5) Defining Relation Schema in SQL (6.6) Indexes Defining Views (6.7)
Murali Mani Constraints. Murali Mani Keys: Primary keys and unique CREATE TABLE Student ( sNum int, sName varchar (20), dept char (2), CONSTRAINT key.
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.
Constraints and Triggers
Foreign Keys Local and Global Constraints Triggers
SQL: Constraints and Triggers
Lecture 05 Views, Constraints
Lecture 12: SQL Friday, October 20, 2000.
Lecture 06: SQL Monday, October 11, 2004.
Lecture 4: SQL Wednesday, April 10, 2002.
SQL – Constraints & Triggers
Lecture 05: SQL Wednesday, October 9, 2002.
Lecture 14: SQL Wednesday, October 31, 2001.
Presentation transcript:

M.P. Johnson, DBMS, Stern/NYU, Sp20041 C : Database Management Systems Lecture #13 Matthew P. Johnson Stern School of Business, NYU Spring, 2004

M.P. Johnson, DBMS, Stern/NYU, Sp Agenda Last time: G&A, modifications, defining schemata, indices This time:, Constraints, Triggers 1. Views 2. Constraints 3. Triggers Homework 2 is due now Future:  Lots of programming for SQL

M.P. Johnson, DBMS, Stern/NYU, Sp Quick review Examples from sqlzoo.netsqlzoo.net

M.P. Johnson, DBMS, Stern/NYU, Sp New topic: Views (6.7) Stored relations physically exist and persist Views are relations that don’t  in text, “table” = stored relation = “base table” Basically names/references given to queries  maybe a relevant subset of a table Employee(ssn, name, department, project, salary) Payroll has access to Employee, others only to Developers CREATE VIEW Developers AS SELECT name, project FROM Employee WHERE department = ‘Development’ CREATE VIEW Developers AS SELECT name, project FROM Employee WHERE department = ‘Development’

M.P. Johnson, DBMS, Stern/NYU, Sp A Different View Person(name, city) Purchase(buyer, seller, product, store) Product(name, maker, category) We have a new virtual table: NYC-view(buyer, seller, product, store) CREATE VIEW NYC-view AS SELECT buyer, seller, product, store FROM Person, Purchase WHERE Person.city = ‘New York’ AND Person.name = Purchase.buyer CREATE VIEW NYC-view AS SELECT buyer, seller, product, store FROM Person, Purchase WHERE Person.city = ‘New York’ AND Person.name = Purchase.buyer

M.P. Johnson, DBMS, Stern/NYU, Sp A Different View Now we can query the view: SELECT name, store FROM NYC -view, Product WHERE NYC -view.product = Product.name AND Product.category = ‘shoes’ SELECT name, store FROM NYC -view, Product WHERE NYC -view.product = Product.name AND Product.category = ‘shoes’ CREATE VIEW NYC-view AS SELECT buyer, seller, product, store FROM Person, Purchase WHERE Person.city = ‘New York’ AND Person.name = Purchase.buyer CREATE VIEW NYC-view AS SELECT buyer, seller, product, store FROM Person, Purchase WHERE Person.city = ‘New York’ AND Person.name = Purchase.buyer

M.P. Johnson, DBMS, Stern/NYU, Sp What happens when we query a view ? SELECT name, NYC-view.store FROM NYC-view, Product WHERE NYC-view.product = Product.name AND Product.category = ‘shoes’ SELECT name, NYC-view.store FROM NYC-view, Product WHERE NYC-view.product = Product.name AND Product.category = ‘shoes’ SELECT name, Purchase.store FROM Person, Purchase, Product WHERE Person.city = ‘ NYC’ AND Person.name = Purchase.buyer AND Purchase.product = Product.name AND Product.category = “shoes” SELECT name, Purchase.store FROM Person, Purchase, Product WHERE Person.city = ‘ NYC’ AND Person.name = Purchase.buyer AND Purchase.product = Product.name AND Product.category = “shoes”

M.P. Johnson, DBMS, Stern/NYU, Sp Can rename view fields Views info: USER_VIEWS CREATE VIEW NYC-view(nycbuyer, nycseller, prod, store) AS SELECT buyer, seller, product, store FROM Person, Purchase WHERE Person.city = ‘NYC’ AND Person.name = Purchase.buyer CREATE VIEW NYC-view(nycbuyer, nycseller, prod, store) AS SELECT buyer, seller, product, store FROM Person, Purchase WHERE Person.city = ‘NYC’ AND Person.name = Purchase.buyer

M.P. Johnson, DBMS, Stern/NYU, Sp More complex views NYC-View is just a subset of a table Views can be arbitrarily complex Imagine the database of student and course records Students get one view:  For each semester, My-courses Professors get another view  For each course, My-students Bursar gets another view, etc.

M.P. Johnson, DBMS, Stern/NYU, Sp Types of Views Views discussed here:  Used in databases  Computed only on-demand – slow at runtime  Always up to date Sometimes talk about “materialized” views  Used in data warehouses  Pre-computed offline – fast at runtime  May have stale data  More later…

M.P. Johnson, DBMS, Stern/NYU, Sp Updating Views How can I insert a tuple into a table that doesn’t exist? Employee(ssn, name, department, project, salary) CREATE VIEW Developers AS SELECT name, project FROM Employee WHERE department = ‘Development’ CREATE VIEW Developers AS SELECT name, project FROM Employee WHERE department = ‘Development’ INSERT INTO Developers VALUES(‘Conrad’, ‘Optimizer’) INSERT INTO Employee(ssn, name, department, project, salary) VALUES(NULL, ‘Conrad’, NULL, ‘Optimizer’, NULL) If we make the following insertion: It becomes:

M.P. Johnson, DBMS, Stern/NYU, Sp Non-Updatable Views Person(name, city) Purchase(buyer, seller, product, store) How can we add the following tuple to the view? (‘NYC’, ‘Nine West’) We don’t know the name of the purchaser cannot set to NULL (why?) To delete: CREATE VIEW City-Store AS SELECT Person.city, Purchase.store FROM Person, Purchase WHERE Person.name = Purchase.buyer CREATE VIEW City-Store AS SELECT Person.city, Purchase.store FROM Person, Purchase WHERE Person.name = Purchase.buyer DROP VIEW City-Store

M.P. Johnson, DBMS, Stern/NYU, Sp New topic: Constraints & Triggers (7) Certain properties we’d like our database to hold  Enforce application semantics e.g., sid is a key  prevent inconsistencies e.g., sname has to be a string, age must be < 200 Modification of tables may break these properties Constrains enforced by either  Preventing actions causing illegal states  Performing compensating actions Triggers are one option

M.P. Johnson, DBMS, Stern/NYU, Sp Constraints in SQL Domain constraints Keys Foreign keys/referential integrity Attribute-level constraints Tuple-level constraints Global constraints: assertions The more complex, the harder/more expensive to check and enforce simplest Most complex

M.P. Johnson, DBMS, Stern/NYU, Sp Denoting primary keys In the CREATE TABLE statement, use:  PRIMARY KEY or UNIQUE Example: If NAME and ADDRESS are together the primary key, it must be written as: CREATE TABLE MovieStar ( name VARCHAR(30) PRIMARY KEY, address VARCHAR(255), gender CHAR(1) ) CREATE TABLE MovieStar ( name VARCHAR(30) PRIMARY KEY, address VARCHAR(255), gender CHAR(1) ) CREATE TABLE MovieStar ( name VARCHAR(30), address VARCHAR(255), gender CHAR(1), PRIMARY KEY (name, address) ) CREATE TABLE MovieStar ( name VARCHAR(30), address VARCHAR(255), gender CHAR(1), PRIMARY KEY (name, address) )

M.P. Johnson, DBMS, Stern/NYU, Sp Effects of primary keys No two tuples may agree on all key atts  Have key  no duplicates at all No nulls allowed in any of the key atts Only one primary key is allowed per table NB: SQL key is slightly different from Relational Model key  In R.M., key fields values  all other field values  In SQL, key field values really are unique NB: no concept of superkey in SQL  Of course, chosen keys should be minimal (why?)

M.P. Johnson, DBMS, Stern/NYU, Sp CREATE TABLE Product ( productID CHAR(10), name CHAR(30), category VARCHAR(20), price INT, UPC CHAR(20) UNIQUE, PRIMARY KEY (productID), UNIQUE (name, category)) CREATE TABLE Product ( productID CHAR(10), name CHAR(30), category VARCHAR(20), price INT, UPC CHAR(20) UNIQUE, PRIMARY KEY (productID), UNIQUE (name, category)) There is at most one PRIMARY KEY; there can be many UNIQUE Multiple keys

M.P. Johnson, DBMS, Stern/NYU, Sp PRIMARY KEY v. UNIQUE Can use the UNIQUE keyword (instead of PRIMARY KEY) in (almost) same way  Unique keys are…not unique  NULLs allowed, and multiple NULLs allowed (why?) Example: If NAME and ADDRESS are together unique, we can write: CREATE TABLE MovieStar ( name VARCHAR(30) UNIQUE, address VARCHAR(255), gender CHAR(1) ) CREATE TABLE MovieStar ( name VARCHAR(30) UNIQUE, address VARCHAR(255), gender CHAR(1) ) CREATE TABLE MovieStar ( name VARCHAR(30), address VARCHAR(255), gender CHAR(1), UNIQUE (name, address) ) CREATE TABLE MovieStar ( name VARCHAR(30), address VARCHAR(255), gender CHAR(1), UNIQUE (name, address) )

M.P. Johnson, DBMS, Stern/NYU, Sp Indices & keys Close affinity between indices and keys Want to keep values unique (key)  need easy way to check for existing values (index) In many implementations (like Oracle): creating keys (primary or unique) automatically creates indices Explicit unique index creation:  In effect, automatically creates key Index info: USER_INDEXES CREATE UNIQUE INDEX MyIndex on MyTable(a,b,c)

M.P. Johnson, DBMS, Stern/NYU, Sp Foreign Key Constraint ActedIn(ActorName, MovieName) Movies(MovieName, year) If MovieName in ActedIn is a foreign key for Movies, then: 1. The referenced atts must be a key in the ref-ed table 2. All non-null foreign key values must appear in the referenced table ActorNameMovieNameMovieYear TitleYear (1) (2) ActedIn Movies

M.P. Johnson, DBMS, Stern/NYU, Sp Foreign key example Recall, ActedIn has FK MovieName...  Movies(MovieName, year)  (Fatal Attraction, 1987)  ActedIn(ActorName, MovieName)  (Michael Douglas, Fatal Attraction) ActorNameMovieNameMovieYear M.DouglasFatal Attract1987 TitleYear Fatal Attraction1987 (1) (2) ActedIn Movies

M.P. Johnson, DBMS, Stern/NYU, Sp Declaring Foreign Key Constraints REFERENCES keyword: Or summarize at end: CREATE TABLE ActedIn ( ActorName VARCHAR(30), MovieName VARCHAR(30) REFERENCES Movies(MovieName) ) CREATE TABLE ActedIn ( ActorName VARCHAR(30), MovieName VARCHAR(30) REFERENCES Movies(MovieName) ) CREATE TABLE ActedIn ( ActorName VARCHAR(30), MovieName VARCHAR(30), CONSTRAINT const_name FOREIGN KEY (MovieName) REFERENCES Movies(MovieName)) CREATE TABLE ActedIn ( ActorName VARCHAR(30), MovieName VARCHAR(30), CONSTRAINT const_name FOREIGN KEY (MovieName) REFERENCES Movies(MovieName))

M.P. Johnson, DBMS, Stern/NYU, Sp Constraint example Q: Is this the same as REFERENCES? CREATE TABLE StarrtedIn ( ActorName VARCHAR(30), MovieName VARCHAR(30) CHECK (MovieName IN (SELECT MovieName FROM Movies) ) ) CREATE TABLE StarrtedIn ( ActorName VARCHAR(30), MovieName VARCHAR(30) CHECK (MovieName IN (SELECT MovieName FROM Movies) ) ) ActorNameMovieNameMovieYear M.DouglasFatal Attract1987 TitleYear Fatal Attraction1987 (1) (2) ActedIn Movies

M.P. Johnson, DBMS, Stern/NYU, Sp Dangling tuples result from Can result from: In StarredIn: insert/update In Movies: delete/update Responses: 1. Reject 2. Cascade 3. Set-null

M.P. Johnson, DBMS, Stern/NYU, Sp What happens during updates? SQL has three policies for maintaining referential integrity: Reject violating modifications (default) Cascade: after a delete/update do a delete/update Set-null set foreign-key field to NULL

M.P. Johnson, DBMS, Stern/NYU, Sp Cascading and set-null Cascading: Applies to last two causes:  Deleting exec  Bad exec update  I.e., loss/change of exec referred to Strategy: del/change exec referred to  del/change the reference to exec Loss/change of exec referred to  set reference to null

M.P. Johnson, DBMS, Stern/NYU, Sp Cascading and set-null Cascade/set-null choices independent by att: CREATE TABLE Studio ( name CHAR(30) PRIMARY KEY, address VARCHAR(255), presC# int REFERENCES MovieExec(cert#) ON DELETE SET NULL ON UPDATE CASCADE ) CREATE TABLE Studio ( name CHAR(30) PRIMARY KEY, address VARCHAR(255), presC# int REFERENCES MovieExec(cert#) ON DELETE SET NULL ON UPDATE CASCADE )

M.P. Johnson, DBMS, Stern/NYU, Sp Circular dependencies Sometimes one table refers to another and the other refers to the first  Neither can be inserted without the other Soln involves  Transactions (xacts)  Deferring constraint check until end of xact Constraints can be NOT DEFERABLE (default) or DEFERABLE  DEFERABLE INITIALLY DEFERRED  DEFERABLE INITIALLY IMMEDIATE

M.P. Johnson, DBMS, Stern/NYU, Sp Deferring constraints CREATE TABLE Studio ( name CHAR(30) PRIMARY KEY, address VARCHAR(255), presC# INT UNIQUE REFERENCES MovieExec(cert#) DEFERRABLE INITIALLY DEFERRED ) CREATE TABLE Studio ( name CHAR(30) PRIMARY KEY, address VARCHAR(255), presC# INT UNIQUE REFERENCES MovieExec(cert#) DEFERRABLE INITIALLY DEFERRED )

M.P. Johnson, DBMS, Stern/NYU, Sp Constraints Constraints can be applied to 1. On attributes 2. On tuples Set update and delete actions inde’ly: ON UPDATE not supported by Oracle CREATE TABLE StarredIn ( ActorName VARCHAR(30), MovieName VARCHAR(30) REFERENCES Movies(MovieName) ON DELETE SET CASCADE ) CREATE TABLE StarredIn ( ActorName VARCHAR(30), MovieName VARCHAR(30) REFERENCES Movies(MovieName) ON DELETE SET CASCADE )

M.P. Johnson, DBMS, Stern/NYU, Sp Constraining Attribute Values Constrain invalid values   Any test legal in a WHERE clause Subqueries (but not in Oracle!), etc. The constraint is checked whenever the local attributes it references are changed or added name CHAR(30) NOT NULL gender CHAR(1) CHECK (gender IN (‘F’, ‘M’))

M.P. Johnson, DBMS, Stern/NYU, Sp CREATE TABLE Purchase ( prodName CHAR(30) CHECK (prodName IN SELECT Product.name FROM Product), date DATETIME NOT NULL) CREATE TABLE Purchase ( prodName CHAR(30) CHECK (prodName IN SELECT Product.name FROM Product), date DATETIME NOT NULL) Is this the same as a foreign key?

M.P. Johnson, DBMS, Stern/NYU, Sp Naming domains to constrain values Can define new domains to use as the attribute type: Then update our attribute definition...  gender GenderDomain Note use of VALUE to refer to the att value Named domains are not supported by Oracle CREATE DOMAIN GenderDomain CHAR(1) CHECK (VALUE IN (‘F’, ‘M’)) CREATE DOMAIN GenderDomain CHAR(1) CHECK (VALUE IN (‘F’, ‘M’))

M.P. Johnson, DBMS, Stern/NYU, Sp Among several attributes in one table  Specify at the end of CREATE TABLE CHECK (gender = ‘F’ OR name NOT LIKE ‘Ms.%’) Checked whenever a tuple of the relation is added or updated. CREATE TABLE Sailors ( sid INTEGER, sname CHAR(10), rating INTEGER, age REAL, PRIMARY KEY (sid), CHECK ( rating >= 1 AND rating <= 10) ) CREATE TABLE Sailors ( sid INTEGER, sname CHAR(10), rating INTEGER, age REAL, PRIMARY KEY (sid), CHECK ( rating >= 1 AND rating <= 10) ) More complex constraints

M.P. Johnson, DBMS, Stern/NYU, Sp Adding/deleting named constraints Add: Delete: Constraints info: USER_CONSTRAINTS ALTER TABLE Movie ADD CONSTRAINT Const1 PRIMARY KEY(name) ALTER TABLE Movie ADD CONSTRAINT Const1 PRIMARY KEY(name) ALTER TABLE Movie DROP CONSTRAINT Const1 ALTER TABLE Movie DROP CONSTRAINT Const1

M.P. Johnson, DBMS, Stern/NYU, Sp Assertions (7.4) Constraint on entire database (not table!)  Checked upon any change to DB  Not supported by Oracle CREATE ASSERTION CHECK ( ) Analogous to our assertions in R.A.: Studio(Name, Address, PresC#); MovieExec(Name, Address, Cert#, NetWorth); CREATE ASSERTION RichPres CHECK (NOT EXISTS (SELECT * FROM Studio, MovieExec WHERE presC# = cert# AND netWorth < 10,000,000)) CREATE ASSERTION RichPres CHECK (NOT EXISTS (SELECT * FROM Studio, MovieExec WHERE presC# = cert# AND netWorth < 10,000,000))

M.P. Johnson, DBMS, Stern/NYU, Sp Another assertion example Movie(Title, Year, Length, inColor, StudioName, ProducerC#) Q: Can we w rite this as a tuple constraint? Q: Could we if >=  < ? CREATE ASSERTION SumLength CHECK (10000 >= ALL (SELECT SUM(length) FROM Movie GROUP BY studioName)) CREATE ASSERTION SumLength CHECK (10000 >= ALL (SELECT SUM(length) FROM Movie GROUP BY studioName))

M.P. Johnson, DBMS, Stern/NYU, Sp Another example Q: What does this check? CREATE ASSERTION myAssert CHECK NOT EXISTS( SELECT Product.name FROM Product, Purchase WHERE Product.name = Purchase.prodName GROUP BY Product.name HAVING count(*) > 200) CREATE ASSERTION myAssert CHECK NOT EXISTS( SELECT Product.name FROM Product, Purchase WHERE Product.name = Purchase.prodName GROUP BY Product.name HAVING count(*) > 200)

M.P. Johnson, DBMS, Stern/NYU, Sp Different Constraint Types Q: Why not always use assertions? TypeWhere Declared When activated Guaranteed to hold? Attributewith attributeon insertion or update not if subquery Tuplerelation schema insertion or update to relation not if subquery Assertiondatabase schema on change to any relation mentioned Yes

M.P. Johnson, DBMS, Stern/NYU, Sp Triggers Constraints state what must remain true  DBMS decides when to check Triggers are instructions to perform at explicitly specified times Three aspects:  An event (e.g., update to an attribute)  A condition (e.g., a query to check)  An action (the trigger’s effect) (deletion, update, insertion) When the event occurs, DBMS checks the constraint, and if it is satisfied, performs the action

M.P. Johnson, DBMS, Stern/NYU, Sp Triggers – important points Can replace old row (result of event) with new row Action may be performed before or after event Can refer to old row and new row WHEN clauses tests whether to continue Action may be performed either  For each row involved in event  Once per event Oracle does triggers as PL/SQL programs

M.P. Johnson, DBMS, Stern/NYU, Sp Elements of Triggers 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 an optional 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

M.P. Johnson, DBMS, Stern/NYU, Sp Simple trigger example R(id, data, last-modified)  data is a large string  Last-modified is a newly added date field Goal: whenever data is modified, update last- modified date Could modify all scripts/programs that touch this table  Bad idea Better: user a trigger CREATE TRIGGER UpdateDateTrigger BEFORE UPDATE OF data ON R REFERENCING NEW ROW AS NewTuple FOR EACH STATEMENT BEGIN NewTuple.last-modified = sysdate; END; CREATE TRIGGER UpdateDateTrigger BEFORE UPDATE OF data ON R REFERENCING NEW ROW AS NewTuple FOR EACH STATEMENT BEGIN NewTuple.last-modified = sysdate; END;

M.P. Johnson, DBMS, Stern/NYU, Sp Triggers: Row-level example MovieExec(name, address, cert#, netWorth) “If someone decreases a movie executive’s net worth, I want the database to reset itself to the previous net worth.” CREATE TRIGGER NetWorthTrigger AFTER UPDATE OF netWorth ON MovieExec REFERENCING NEW ROW AS NewTuple OLD ROW AS OldTuple FOR EACH ROW WHEN (OldTuple.netWorth>NewTuple.netWorth) UPDATE MovieExec SET netWorth = oldTuple.netWorth WHERE cert# = newTuple.cert#) CREATE TRIGGER NetWorthTrigger AFTER UPDATE OF netWorth ON MovieExec REFERENCING NEW ROW AS NewTuple OLD ROW AS OldTuple FOR EACH ROW WHEN (OldTuple.netWorth>NewTuple.netWorth) UPDATE MovieExec SET netWorth = oldTuple.netWorth WHERE cert# = newTuple.cert#)

M.P. Johnson, DBMS, Stern/NYU, Sp Triggers: Table-level example MovieExec(name, address, cert#, netWorth) “If someone updates the net worth of one movie exec so that the average net worth of all movie execs becomes less than $50,000, I want the database to reset itself.” CREATE TRIGGER AvgNetWorthTrigger AFTER UPDATE OF netWorth ON MovieExec REFERENCING OLD TABLE AS OldStuff, NEW TABLE AS NewStuff FOR EACH STATEMENT WHEN (50000 > (SELECT AVG(netWorth) FROM MovieExec)) BEGIN DELETE FROM MovieExec WHERE (Name, address, cert#, netWorth) IN NewStuff; INSERT INTO MovieExec (SELECT * FROM OldStuff); END; CREATE TRIGGER AvgNetWorthTrigger AFTER UPDATE OF netWorth ON MovieExec REFERENCING OLD TABLE AS OldStuff, NEW TABLE AS NewStuff FOR EACH STATEMENT WHEN (50000 > (SELECT AVG(netWorth) FROM MovieExec)) BEGIN DELETE FROM MovieExec WHERE (Name, address, cert#, netWorth) IN NewStuff; INSERT INTO MovieExec (SELECT * FROM OldStuff); END;

M.P. Johnson, DBMS, Stern/NYU, Sp End Examples from sqlzoo.netsqlzoo.net For next time: read 8.1-2