CS411 Database Systems Kazuhiro Minami 06: SQL. Constraints & Triggers Foreign Keys Local and Global Constraints Triggers.

Slides:



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

Chapter 7 Notes on Foreign Keys Local and Global Constraints Triggers.
SQL Constraints and Triggers
Triggers. Triggers: Motivation Assertions are powerful, but the DBMS often can’t tell when they need to be checked. Attribute- and tuple-based checks.
Constraints and Triggers Foreign Keys Local and Global Constraints Triggers.
Constraints We have discussed three types of integrity constraints: primary keys, not null constraints, and unique constraints. CREATE TABLE Movies ( title.
1 Constraints Foreign Keys Local and Global Constraints Triggers Source: slides by Jeffrey Ullman.
CPSC-608 Database Systems Fall 2010 Instructor: Jianer Chen Office: HRBB 315C Phone: Notes #4.
1 Constraints Foreign Keys Local and Global Constraints Triggers.
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,
1 Constraints Foreign Keys Local and Global Constraints 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,
CPSC-608 Database Systems Fall 2008 Instructor: Jianer Chen Office: HRBB 309B Phone: Notes #4.
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.
Triggers.
CMPT 354, Simon Fraser University, Fall 2008, Martin Ester 157 Database Systems I SQL Constraints and Triggers.
CPSC-608 Database Systems Fall 2011 Instructor: Jianer Chen Office: HRBB 315C Phone: Notes #2.
DB Modifications Modification = insert + delete + update. Insertion of a Tuple INSERT INTO relation VALUES (list of values). Inserts the tuple = list of.
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.
SCUHolliday - coen 1789–1 Schedule Today: u Constraints, assertions, triggers u Read Sections , 7.4. Next u Triggers, PL/SQL, embedded SQL, JDBC.
Constraints on Relations Foreign Keys Local and Global Constraints Triggers Following lecture slides are modified from Jeff Ullman’s slides
Databases 1 Fourth lecture. Rest of SQL Defining a Database Schema Views Foreign Keys Local and Global Constraints Triggers 2.
Winter 2006Keller, Ullman, Cushing9–1 Constraints Commercial relational systems allow much more “fine-tuning” of constraints than do the modeling languages.
1 IT 244 Database Management System Lecture 11 More SQL Constraints &Triggers, SQL Authorization,Transactions Foreign Keys, Local and Global Constraints,
Onsdag The concepts in a relation data model SQL DDL DML.
1 ICS 184: Introduction to Data Management Lecture Note 11: Assertions, Triggers, and Index.
+ Assignment 5 Q’s CSCI 2141 W Foreign Key issue CONSTRAINT fk_model FOREIGN KEY (model) REFERENCES Desktop(Model) Problem – can’t have it reference.
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 Database Systems Defining Database Schema Views.
Constraints and Triggers. What’s IC? Integrity Constraints define the valid states of SQL-data by constraining the values in the base tables. –Restrictions.
Advanced SQL Concepts - Checking of Constraints CIS 4301 Lecture Notes Lecture /6/2006.
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.
Himanshu GuptaCSE 532-SQL-1 SQL. Himanshu GuptaCSE 532-SQL-2 Why SQL? SQL is a very-high-level language, in which the programmer is able to avoid specifying.
SCUHolliday - coen 1787–1 Schedule Today: u Subqueries, Grouping and Aggregation. u Read Sections Next u Modifications, Schemas, Views. u Read.
Databases : SQL-Schema Definition and View 2007, Fall Pusan National University Ki-Joune Li These slides are made from the materials that Prof. Jeffrey.
Database Management COP4540, SCS, FIU Database Trigger.
1 Constraints, Views, Indexes Foreign Keys Constraints Triggers Virtual and Materialized Views Speeding Accesses to Data.
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.
1 Introduction to Database Systems, CS420 SQL Constraints.
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.
1 Introduction to Database Systems, CS420 SQL JOIN, Aggregate, Grouping, HAVING and DML Clauses.
CPSC-310 Database Systems
Slides are reused by the approval of Jeffrey Ullman’s
Outerjoins, Grouping/Aggregation Insert/Delete/Update
CMSC-461 Database Management Systems
The Relational Model.
Constraints and Triggers
Foreign Keys Local and Global Constraints Triggers
CPSC-310 Database Systems
Database Design: DBS CB, 2nd Edition
Introduction to Database Systems, CS420
Introduction to Database Systems, CS420
CPSC-608 Database Systems
CPSC-310 Database Systems
CPSC-310 Database Systems
2018, Fall Pusan National University Ki-Joune Li
CMSC-461 Database Management Systems
CPSC-608 Database Systems
CPSC-608 Database Systems
SQL – Constraints & Triggers
CPSC-608 Database Systems
Presentation transcript:

CS411 Database Systems Kazuhiro Minami 06: SQL

Constraints & Triggers Foreign Keys Local and Global Constraints Triggers

Integrity Constraints in SQL New information added to a database could be wrong in a variety of ways –Typographical or transcription errors in manually entered data Difficult to write application programs to check the integrity (correctness) of data on every insertion, deletion, and update command. SQL provides a variety of techniques for expressing integrity constraints as part of the database schema

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 many constraints.

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

Foreign Keys Sells(bar, beer, price) We might expect that a beer value is a real beer --- something appearing in Beers.name. A constraint that requires a beer in Sells to be a beer in Beers is called a foreign - key (referential integrity) constraint.

Foreign-key Constraints Corresponds to Referential Integrity Constraints in E/R modeling BeersSells sells

Example Sells Beers Blind pig Super Dry $3 Blind pig Samuel Adams $4 bar beer price Super Dry Asahi name manf Violation of the foreign-key constraint

Expressing Foreign Keys Use the keyword REFERENCES, either: 1.Within the declaration of an attribute, when only one attribute is involved. REFERENCES ( ) 1.As an element of the schema, as: FOREIGN KEY ( ) REFERENCES ( ) Referenced attributes must be declared PRIMARY KEY or UNIQUE

Example: With Attribute CREATE TABLE Beers ( nameCHAR(20) PRIMARY KEY, manfCHAR(20) ); CREATE TABLE Sells ( barCHAR(20), beerCHAR(20) REFERENCES Beers(name), priceREAL ); Foreign key Referenced attribute

Example: As Element CREATE TABLE Beers ( nameCHAR(20) PRIMARY KEY, manfCHAR(20) ); CREATE TABLE Sells ( barCHAR(20), beerCHAR(20), priceREAL, FOREIGN KEY(beer) REFERENCES Beers(name)); Foreign-key definition

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

Case 1: Insertion or Update to R Sells (= R) Beers (= S) Blind pig Super Dry $3 bar beer price Super Dry Asahi name manf Blind pig Samuel Adams $4 Dangling tuple

Actions Taken -- 1 An insert or update to Sells that introduces a nonexistent beer must be rejected.

Case 2: Deletion or Update to S Sells (= R) Beers (= S) Blind pig Super Dry $3 bar beer price Super Dry Asahi name manf Blind pig Samuel Adams $4 The second tuple in Sells has become dangle. Samuel Adams The Boston Beer Company

Actions Taken -- 2 The three possible ways to handle beers that suddenly cease to exist are: 1.Default : Reject the modification. 2.Cascade : Make the same changes in Sells. - Deleted beer: delete Sells tuple. - Updated beer: change value in Sells. 3.Set NULL : Change the beer to NULL.

Cascade Strategy Suppose we delete the Bud tuple from Beers. –Then delete all tuples from Sells that have beer = ’Bud’. Suppose we update the Bud tuple by changing ’Bud’ to ’Budweiser’. –Then change all Sells tuples with beer = ’Bud’ so that beer = ’Budweiser’.

Example: Cascade Sells Beers Blind pig Super Dry $3 bar beer pricename manf Blind pig Samuel Adams $4 Super Dry Asahi Samuel Adams The Boston Beer Company Bitter

Example: Set NULL Suppose we delete the Bud tuple from Beers. –Change all tuples of Sells that have beer = ’Bud’ to have beer = NULL. Suppose we update the Bud tuple by changing ’Bud’ to ’Budweiser’. –Same change.

Example: Set NULL Sells Beers Blind pig Super Dry $3 bar beer pricename manf Blind pig Samuel Adams $4 Super Dry Asahi Samuel Adams The Boston Beer Company BitterNULL

When you create the table, specify which of the three options you want to use. CREATE TABLE Customers ( customerName CHAR(20) REFERENCES MasterList(name) ON DELETE CASCADE, city CHAR(20), state CHAR(2), zip CHAR (5), FOREIGN KEY (city, state, zip) REFERENCES GoodAddresses (city, state, zip) ON UPDATE CASCADE ON DELETE SET NULL ); CREATE TABLE Customers ( customerName CHAR(20) REFERENCES MasterList(name) ON DELETE CASCADE, city CHAR(20), state CHAR(2), zip CHAR (5), FOREIGN KEY (city, state, zip) REFERENCES GoodAddresses (city, state, zip) ON UPDATE CASCADE ON DELETE SET NULL ); Default: reject all UPDATEs to MasterList that violate referential integrity

Attribute-Based Checks: You can also check an attribute value at INSERT/UPDATE time CREATE TABLE Sells ( barCHAR(20), beerCHAR(20)CHECK ( beer IN (SELECT name FROM Beers)), priceREAL CHECK ( price <= 5.00 ) ); Use a subquery if you need to mention other attributes or relations

CHECK is never equivalent to a foreign key constraint. Employee Name DepartmentHourly Wage WinslettToy10.00 Name Toy Complaint Development Employees Departments Name Complaint Development With a FOREIGN KEY constraint, the change in Departments will be reflected in Employees. With CHECK, the change in Departments will not be reflected in Employees.

Tuple-Based Checks: You can also check a combination of attribute values at INSERT/UPDATE time Only Joe’s Bar can sell beer for more than $5: CREATE TABLE Sells ( barCHAR(20), beerCHAR(20), priceREAL, CHECK (bar = ’Joe’’s Bar’ OR price <= 5.00) );

For more complex constraints, declare standalone ASSERTIONs. CREATE ASSERTION assertionName CHECK ( condition ); No bar can charge more than $5 on average for beer. CREATE ASSERTION NoExpensiveBars CHECK ( NOT EXISTS ( SELECT bar FROM Sells GROUP BY bar HAVING 5.00 < AVG(price) )); CREATE ASSERTION NoExpensiveBars CHECK ( NOT EXISTS ( SELECT bar FROM Sells GROUP BY bar HAVING 5.00 < AVG(price) )); Bars with an average price above $5

There cannot be more bars than drinkers. Drinkers(name, addr, phone) Bars(name, addr, license) CREATE ASSERTION FewBars CHECK ( (SELECT COUNT (*) FROM Bars) <= (SELECT COUNT (*) FROM DRINKERS) ); CREATE ASSERTION FewBars CHECK ( (SELECT COUNT (*) FROM Bars) <= (SELECT COUNT (*) FROM DRINKERS) );

In theory, every ASSERTION is checked after every INSERT/ DELETE/ UPDATE. In practice, the DBMS only has to check sometimes: Adding a drinker can’t violate FewBars. Removing a bar can’t violate NoExpensiveBars. Lowering a beer price can’t violate NoExpensiveBars. But is the DBMS smart enough to figure this out?

You can help your not-so-smart DBMS by using TRIGGERs instead of ASSERTIONS. A trigger is an ECA rule: When Event occurs If Condition doesn’t hold Then do Action E.g., an INSERT / DELETE / UPDATE to relation R Any SQL Boolean condition Any SQL statements

You can use triggers to code very complex stuff. You can allow your users to update their views --- but you catch their updates and rewrite them to behave the way you want, avoiding view anomalies. You can encode new strategies for handling violations of constraints, different from what the DBMS offers.

If someone inserts an unknown beer into Sells(bar, beer, price), add it to Beers with a NULL manufacturer. CREATE TRIGGER BeerTrig AFTER INSERT ON Sells REFERENCING NEW ROW AS NewTuple FOR EACH ROW WHEN (NewTuple.beer NOT IN (SELECT name FROM Beers)) INSERT INTO Beers(name) VALUES(NewTuple.beer); The event The condition The action

Syntax for naming the trigger CREATE TRIGGER name CREATE OR REPLACE TRIGGER name Useful when there is a trigger with that name and you want to modify the trigger.

Syntax for describing the condition BEFORE AFTER INSTEAD OF INSERT DELETE UPDATE UPDATE ON attribute ON relationName Only if the relation is a view Take one element from each of the three columns:

You can execute a trigger once per modified tuple, or once per triggering statement. Statement-level triggers execute once for each SQL statement that triggers them, regardless of how many tuples are modified. Row level triggers are executed once for each modified tuple. The default Request explicitly by including FOR EACH ROW

Your condition & action can refer to the tuples being inserted/deleted/updated INSERT statements imply a new tuple (for row- level) or new set of tuples (for statement-level). DELETE implies an old tuple (row-level) or table (statement-level). UPDATE implies both. Syntax: REFERENCING [NEW OLD][ROW TABLE] AS name Pick one “No raise over 10%.”

No condition Any boolean-valued Condition is ok in WHEN Condition. BEFORE AFTER INSTEAD OF INSERT DELETE UPDATE UPDATE OF attribute ON relationName Evaluate the condition on the instance before the event Evaluate the condition on the instance after the event

The Action is a sequence of SQL statements (modifications). Surround them by BEGIN... END if there is more than one. But queries make no sense in an action, so we are really limited to modifications.

Remember bars that raise the price of a beer by > $1. CREATE TRIGGER PriceTrig AFTER UPDATE OF price ON Sells REFERENCING OLD ROW AS old NEW ROW AS new FOR EACH ROW WHEN (new.price > old.price ) INSERT INTO NastyBars VALUES(new.bar); The event = changes to prices Updates let us talk about old and new tuples We need to consider each price change Condition: a raise in price > $1 When the price change is great enough, add the bar to NastyBars Sells(bar, beer, price) NastyBars(bar)

Triggers are great for implementing view updates. We cannot insert into Developers --- it is a view. But we can use an INSTEAD OF trigger to turn a (name, project) triple into an insertion of a tuple (name, `Development’, project) to Employee.

Example: 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(“Joe”, “Optimizer”) INSERT INTO Employee VALUES(NULL, “Joe”, NULL, “Optimizer”, NULL) If we make the following insertion: It becomes: This must be “Development”

Allow insertions into Developers CREATE TRIGGER AllowInsert INSTEAD OF INSERT ON Developers REFERENCING NEW ROW AS new FOR EACH ROW BEGIN INSERT INTO Empolyees(name, department, project) VALUES(new.name, `Development’, new.project); END;