Chapter 7: Constraints and Triggers. Foreign Keys Local and Global Constraints Triggers

Similar documents
CS 464/564 Introduction to Database Management System Instructor: Abdullah Mueen

Constraints. Local and Global Constraints Triggers

Constraints and Triggers

Databases 1. Defining Tables, Constraints

From E/R Diagrams to Relations

Design Techniques. 1. Avoid redundancy 2. Limit the use of weak entity sets 3. Don t use an entity set when an attribute will do

SQL DATA DEFINITION LANGUAGE

SQL: Data Definition Language

SQL DATA DEFINITION LANGUAGE

SQL DATA DEFINITION LANGUAGE

A tuple is dangling if it doesn't join with any

Constraints, Views & Indexes. Running Example. Kinds of Constraints INTEGRITY CONSTRAINTS. Keys Foreign key or referential integrity constraints

CS54100: Database Systems

CS W Introduction to Databases Spring Computer Science Department Columbia University

Creating Tables, Defining Constraints. Rose-Hulman Institute of Technology Curt Clifton

Where Are We? Next Few Lectures. Integrity Constraints Motivation. Constraints in E/R Diagrams. Keys in E/R Diagrams

Views, Indexes, Authorization. Views. Views 8/6/18. Virtual and Materialized Views Speeding Accesses to Data Grant/Revoke Priviledges

SQL: Data Definition Language. csc343, Introduction to Databases Diane Horton Fall 2017

Announcements (September 18) SQL: Part II. Solution 1. Incomplete information. Solution 3? Solution 2. Homework #1 due today (11:59pm)

SQL: Part III. Announcements. Constraints. CPS 216 Advanced Database Systems

SQL: Part II. Announcements (September 18) Incomplete information. CPS 116 Introduction to Database Systems. Homework #1 due today (11:59pm)

Database Management System Dr. S. Srinath Department of Computer Science & Engineering Indian Institute of Technology, Madras Lecture No.

Introduction to Data Management CSE 344

Chapter 7 Constraints and Triggers. Spring 2011 Instructor: Hassan Khosravi

Introduction to SQL. Multirelation Queries Subqueries. Slides are reused by the approval of Jeffrey Ullman s

Transactions, Views, Indexes. Controlling Concurrent Behavior Virtual and Materialized Views Speeding Accesses to Data

Introduction to Database Systems CSE 414

Summary Modifications. Database Construction (and Usage) Explicit attribute lists. Insertions with queries. Quiz. Default values

CS 464/564 Introduction to Database Management System Instructor: Abdullah Mueen

SQL: Part II. Introduction to Databases CompSci 316 Fall 2018

Subqueries. Must use a tuple-variable to name tuples of the result

Interpretation is not exactly ëmissing value." There could be many reasons why no value is

Announcements (September 21) SQL: Part III. Triggers. Active data. Trigger options. Trigger example

Module 9: Managing Schema Objects

Introduction to Data Management CSE 344

CSC 343 Winter SQL: Aggregation, Joins, and Triggers MICHAEL LIUT

SQL Continued! Outerjoins, Aggregations, Grouping, Data Modification

Integrity Constraints (Reminder)

EXTENDED RELATIONAL ALGEBRA OUTERJOINS, GROUPING/AGGREGATION INSERT/DELETE/UPDATE

SQL: Triggers, Views, Indexes. Introduction to Databases CompSci 316 Fall 2018

The Relational Model. Relational Data Model Relational Query Language (DDL + DML) Integrity Constraints (IC)

Relational Model History. COSC 416 NoSQL Databases. Relational Model (Review) Relation Example. Relational Model Definitions. Relational Integrity

DATA AND SCHEMA MODIFICATIONS CHAPTERS 4,5 (6/E) CHAPTER 8 (5/E)

Database Design and Programming

Comp 5311 Database Management Systems. 4b. Structured Query Language 3

SQL: A COMMERCIAL DATABASE LANGUAGE. Complex Constraints

The Relational Model of Data (ii)

Chapter 6 The database Language SQL as a tutorial

COMP102: Introduction to Databases, 20

Overview. Data Integrity. Three basic types of data integrity. Integrity implementation and enforcement. Database constraints Transaction Trigger

Chapter 4. Basic SQL. Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

More SQL. Extended Relational Algebra Outerjoins, Grouping/Aggregation Insert/Delete/Update

Introduction to Data Management CSE 344

Databases 2012 Constraints, Triggers, and Views

Introduction to Transactions: Controlling Concurrent "Behavior" Virtual and Materialized Views" Indexes: Speeding Accesses to Data"

Introduction to Data Management. Lecture #17 (SQL, the Never Ending Story )

From Relational Algebra to the Structured Query Language. Rose-Hulman Institute of Technology Curt Clifton

Relational data model

SQL DATA DEFINITION: KEY CONSTRAINTS. CS121: Relational Databases Fall 2017 Lecture 7

Contains slides made by Naci Akkøk, Pål Halvorsen, Arthur M. Keller, Vera Goebel

Why SQL? SQL is a very-high-level language. Database management system figures out best way to execute query

SQL Constraints and Triggers

Domain Constraints Referential Integrity Assertions Triggers. Authorization Authorization in SQL

The Relational Model. Week 2

EGCI 321: Database Systems. Dr. Tanasanee Phienthrakul

Introduction to SQL. Select-From-Where Statements Multirelation Queries Subqueries. Slides are reused by the approval of Jeffrey Ullman s

Introduction to SQL. Select-From-Where Statements Multirelation Queries Subqueries

Databases 1. SQL/PSM and Oracle PL/SQL

Grouping Operator. Applying γ L (R) Recall: Outerjoin. Example: Grouping/Aggregation. γ A,B,AVG(C)->X (R) =??

Structured Query Language Continued. Rose-Hulman Institute of Technology Curt Clifton

Copyright 2016 Ramez Elmasri and Shamkant B. Navathe

Lecture 2 SQL. Instructor: Sudeepa Roy. CompSci 516: Data Intensive Computing Systems

The Relational Model 2. Week 3

Slides by: Ms. Shree Jaswal

Databases-1 Lecture-01. Introduction, Relational Algebra

DATABASE TECHNOLOGY - 1MB025 (also 1DL029, 1DL300+1DL400)

CS 4604: Introduc0on to Database Management Systems. B. Aditya Prakash Lecture #4: SQL---Part 2

The Relational Data Model. Data Model

Chapter 4. Basic SQL. SQL Data Definition and Data Types. Basic SQL. SQL language SQL. Terminology: CREATE statement

Concepts of Database Management Seventh Edition. Chapter 4 The Relational Model 3: Advanced Topics

Basic SQL. Basic SQL. Basic SQL

CMPT 354: Database System I. Lecture 3. SQL Basics

SQL: A COMMERCIAL DATABASE LANGUAGE. Data Change Statements,

CHAPTER4 CONSTRAINTS

Introduction to SQL SELECT-FROM-WHERE STATEMENTS SUBQUERIES DATABASE SYSTEMS AND CONCEPTS, CSCI 3030U, UOIT, COURSE INSTRUCTOR: JAREK SZLICHTA

Chapter 14. Active Databases. Database Systems(Part 2) p. 200/286

Chapter 6 The database Language SQL as a tutorial

Outerjoins, Constraints, Triggers

SQL: Concepts. Todd Bacastow IST 210: Organization of Data 2/17/ IST 210

Introduction to Data Management. Lecture #4 (E-R Relational Translation)

CSCD43: Database Systems Technology. Lecture 4

Integrity and Security

CS2300: File Structures and Introduction to Database Systems

Announcements. Database Design. Database Design. Database Design Process. Entity / Relationship Diagrams. Introduction to Data Management CSE 344

Asst. Prof. Lipyeow Lim Information & Computer Science Department University of Hawaii at Manoa

Introduction to Data Management. Lecture 16 (SQL: There s STILL More...) It s time for another installment of...

Debapriyo Majumdar DBMS Fall 2016 Indian Statistical Institute Kolkata

Chapter 4. The Relational Model

PostgreSQL 7.3 Documentation Prev Chapter 2. Data Definition Next

SQL Constraints and Triggers. Week 11

Transcription:

Chapter 7: Constraints and Triggers Foreign Keys Local and Global Constraints Triggers 27

Constraints and Triggers! A constraint is a relationship among data elements that the DBMS is required to enforce.! Example: key constraints.! Triggers are only executed when a specified condition occurs, e.g., insertion of a tuple.! Easier to implement than complex constraints. 28

Kinds of Constraints! Keys.! Foreign-key, or referential-integrity.! Value-based constraints.! Constrain values of a particular attribute.! Tuple-based constraints.! Relationship among components.! Assertions: any SQL boolean expression. 29

Foreign Keys! Consider Relation Sells(store, candy, price).! We might expect that a candy value is a real candy --- something appearing in Candies.name.! A constraint that requires a candy in Sells to be a candy in Candies is called a foreign -key constraint. 30

Expressing Foreign Keys! Use the keyword REFERENCES, either:! Within the declaration of an attribute (only for one-attribute keys).! As an element of the schema: FOREIGN KEY ( <list of attributes> ) REFERENCES <relation> ( <attributes> )! Referenced attributes must be declared PRIMARY KEY or UNIQUE. 31

Example: With Attribute CREATE TABLE Candies ( name CHAR(20) PRIMARY KEY, manf CHAR(20) ); CREATE TABLE Sells ( store CHAR(20), candy CHAR(20) REFERENCES Candies(name), price REAL ); 32

Example: As Element CREATE TABLE Candies ( name CHAR(20) PRIMARY KEY, manf CHAR(20) ); CREATE TABLE Sells ( store CHAR(20), candy CHAR(20), price REAL, FOREIGN KEY(candy) REFERENCES Candies(name)); 33

Enforcing Foreign-Key Constraints! If there is a foreign-key constraint from attributes of relation R to a key of relation S, two violations are possible:! An insert or update to R introduces values not found in S.! A deletion or update to S causes some tuples of R to dangle. 34

Actions Taken --- (1)! Suppose R = Sells, S = Candies.! An insert or update to Sells that introduces a nonexistent candy must be rejected.! A deletion or update to Candies that removes a candy value found in some tuples of Sells can be handled in three ways (next slide). 35

Actions Taken --- (2)! Default : Reject the modification.! Cascade : Make the same changes in Sells.! Deleted candy: delete Sells tuple.! Updated candy: change value in Sells.! Set NULL : Change the candy to NULL. 36

Example: Cascade! Delete the Twizzler tuple from Candies:! Then delete all tuples from Sells that have candy = Twizzler.! Update the Twizzler tuple by changing Twizzler to Twiz. :! Then change all Sells tuples with candy = Twizzler so that candy = Twiz.. 37

Example: Set NULL! Delete the Twizzler tuple from Candies:! Change all tuples of Sells that have candy = Twizzler to have candy = NULL.! Update the Twizzler tuple by changing Twizzler to Twiz. :! Same change. 38

Choosing a Policy! When we declare a foreign key, we may choose policies SET NULL or CASCADE independently for deletions and updates.! Follow the foreign-key declaration by: ON [UPDATE, DELETE][SET NULL, CASCADE]! Two such clauses may be used.! Otherwise, the default (reject) is used. 39

Example CREATE TABLE Sells ( store CHAR(20), candy CHAR(20), price REAL, FOREIGN KEY(candy) REFERENCES Candies(name) ON DELETE SET NULL ON UPDATE CASCADE ); 40

Attribute-Based Checks! Constraints on the value of a particular attribute.! Add: CHECK( <condition> ) to the declaration for the attribute.! The condition may use the name of the attribute, but any other relation or attribute name must be in a subquery. 41

Example CREATE TABLE Sells ( store CHAR(20), candy CHAR(20) CHECK ( candy IN (SELECT name FROM Candies)), price REAL CHECK ( price <= 5.00 ) ); 42

Timing of Checks! Attribute-based checks are performed only when a value for that attribute is inserted or updated.! Example: CHECK (price <= 5.00) checks every new price and rejects the modification (for that tuple) if the price is more than $5.! Example: CHECK (candy IN (SELECT name FROM Candies))is not checked if a candy is deleted from Candies (unlike foreign-keys). 43

Tuple-Based Checks! CHECK ( <condition> ) may be added as a relation-schema element.! The condition may refer to any attribute of the relation.! But any other attributes or relations require a subquery.! Checked on insert or update only. 44

Example: Tuple-Based Check! Only 7-11 can sell candy for more than $5: CREATE TABLE Sells ( store CHAR(20), candy CHAR(20), price REAL, CHECK (store = 7-11 OR price <= 5.00) ); 45

Assertions! These are database-schema elements, like relations or views.! Defined by: CREATE ASSERTION <name> CHECK ( <condition> );! Condition may refer to any relation or attribute in the database schema. 46

Example: Assertion! In Sells(store, candy, price), no store may charge an average of more than $5. CREATE ASSERTION NoRipoffStores CHECK ( NOT EXISTS ( )); SELECT store FROM Sells GROUP BY stores HAVING AVG(price) > 5.00 Stores with an average price above $5 47

Example: Assertion! In Consumers(name, addr, phone) and Stores (name, addr, license), there cannot be more stores than consumers. CREATE ASSERTION FewStore CHECK ( (SELECT COUNT(*) FROM Stores) <= (SELECT COUNT(*) FROM Consumers) ); 48

Timing of Assertion Checks! In principle, we must check every assertion after every modification to any relation of the database.! A clever system can observe that only certain changes could cause a given assertion to be violated.! Example: No change to Candies can affect FewStore. Neither can an insertion to Consumers. 49

Triggers: Motivation! Assertions are powerful, but the DBMS often can t tell when they need to be checked.! Attribute- and tuple-based checks are checked at known times, but are not powerful.! Triggers let the user decide when to check for a powerful condition. 2

Event-Condition-Action Rules! Another name for trigger is ECA rule, or event-condition-action rule.! Event : typically a type of database modification, e.g., insert on Sells.! Condition : Any SQL boolean-valued expression.! Action : Any SQL statements. 3

Preliminary Example: A Trigger! Instead of using a foreign-key constraint and rejecting insertions into Sells(store, candy, price) with unknown candies, a trigger can add that candy to Candies, with a NULL manufacturer. 4

Example: Trigger Definition CREATE TRIGGER CandyTrig AFTER INSERT ON Sells REFERENCING NEW ROW AS NewTuple FOR EACH ROW WHEN (NewTuple.candy NOT IN (SELECT name FROM Candies)) INSERT INTO Candies(name) VALUES(NewTuple.candy); 5

Example: Trigger Definition The event CREATE TRIGGER CandyTrig AFTER INSERT ON Sells REFERENCING NEW ROW AS NewTuple FOR EACH ROW WHEN (NewTuple.candy NOT IN (SELECT name FROM Candies)) INSERT INTO Candies(name) VALUES(NewTuple.candy); The condition The action 6

Options: CREATE TRIGGER! CREATE TRIGGER <name> 7

Options: The Event! AFTER can be BEFORE.! Also, INSTEAD OF, if the relation is a view.! A great way to execute view modifications: have triggers translate them to appropriate modifications on the base tables.! INSERT can be DELETE or UPDATE.! And UPDATE can be UPDATE... ON a particular attribute. 8

Options: FOR EACH ROW! Triggers are either row-level or statement-level.! FOR EACH ROW indicates row-level; its absence indicates statement-level.! Row level triggers : execute once for each modified tuple.! Statement-level triggers : execute once for an SQL statement, regardless of how many tuples are modified. 9

Options: REFERENCING! INSERT statements imply a new tuple (for row-level) or new table (for statement-level).! The table is the set of inserted tuples.! DELETE implies an old tuple or table.! UPDATE implies both.! Refer to these by [NEW OLD][ROW TABLE] AS <name> 10

Options: The Condition! Any boolean-valued condition is appropriate.! It is evaluated before or after the triggering event, depending on whether BEFORE or AFTER is used in the event.! Access the new/old tuple or set of tuples through the names declared in the REFERENCING clause. 11

Options: The Action! There can be more than one SQL statement in the action.! Surround by BEGIN... END if there is more than one.! But queries make no sense in an action, so we are really limited to modifications. 12

Another Example! Using Sells(store, candy, price) and a unary relation RipoffStores(store) created for the purpose, maintain a list of stores that raise the price of any candy by more than $1. 13

The Trigger CREATE TRIGGER PriceTrig AFTER UPDATE OF price ON Sells REFERENCING OLD ROW AS ooo NEW ROW AS nnn FOR EACH ROW WHEN(nnn.price > ooo.price + 1.00) INSERT INTO RipoffStores VALUES(nnn.store); 14

The Trigger CREATE TRIGGER PriceTrig AFTER UPDATE OF price ON Sells REFERENCING OLD ROW AS ooo NEW ROW AS nnn FOR EACH ROW WHEN(nnn.price > ooo.price + 1.00) INSERT INTO RipoffStores VALUES(nnn.store); Updates let us talk about old and new tuples We need to consider each price change The event only changes to prices Condition: a raise in price > $1 When the price change is great enough, add the store to RipoffStores 15

Triggers on Views! Generally, it is impossible to modify a view, because it doesn t exist.! But an INSTEAD OF trigger lets us interpret view modifications in a way that makes sense.! Example: We ll design a view Synergy that has (consumer, candy, store) triples such that the store sells the candy, the consumer frequents the store and likes the candy. 16

Example: The View CREATE VIEW Synergy AS SELECT Likes.consumer, Likes.candy, Sells.store FROM Likes, Sells, Frequents WHERE Likes.consumer = Frequents.consumer AND Likes.candy = Sells.candy AND Sells.store = Frequents.store; 17

Example: The View Pick one copy of each attribute CREATE VIEW Synergy AS SELECT Likes.consumer, Likes.candy, Sells.store FROM Likes, Sells, Frequents WHERE Likes.consumer = Frequents.consumer AND Likes.candy = Sells.candy AND Sells.store = Frequents.store; Natural join of Likes, Sells, and Frequents 18

Interpreting a View Insertion! We cannot insert into Synergy --- it is a view.! But we can use an INSTEAD OF trigger to turn a (consumer, candy, store) triple into three insertions of projected pairs, one for each of Likes, Sells, and Frequents.! The Sells.price will have to be NULL. 19

The Trigger CREATE TRIGGER ViewTrig INSTEAD OF INSERT ON Synergy REFERENCING NEW ROW AS n FOR EACH ROW BEGIN INSERT INTO LIKES VALUES(n.consumer, n.candy); INSERT INTO SELLS(store, candy) VALUES(n.store, n.candy); INSERT INTO FREQUENTS VALUES(n.consumer, n.store); END; 20