SQL – Constraints & Triggers

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.
Chapter 7 Notes on Foreign Keys Local and Global Constraints Triggers.
SQL Constraints and Triggers
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5 More SQL: Complex Queries, Triggers, Views, and Schema Modification.
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.
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.
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.
Creating Tables, Defining Constraints Rose-Hulman Institute of Technology Curt Clifton.
SQL Keys and Constraints Justin Maksim. Key Declaration Key constraint defined within the CREATE TABLE command Key can be declared using either the PRIMARY.
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.
DB Modifications Modification = insert + delete + update. Insertion of a Tuple INSERT INTO relation VALUES (list of values). Inserts the tuple = list of.
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.
CSE314 Database Systems More SQL: Complex Queries, Triggers, Views, and Schema Modification Doç. Dr. Mehmet Göktürk src: Elmasri & Navanthe 6E Pearson.
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.
CS411 Database Systems Kazuhiro Minami 06: SQL. Constraints & Triggers Foreign Keys Local and Global Constraints Triggers.
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.
Dec 8, 2003Murali Mani Constraints B term 2004: lecture 15.
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 Database Systems Defining Database Schema Views.
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.
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.
Constraining Attribute Values Constrain invalid values –NOT NULL –gender CHAR(1) CHECK (gender IN (‘F’, ‘M’)) –MovieName CHAR(30) CHECK (MovieName IN (SELECT.
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.
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.
More SQL: Complex Queries, Triggers, Views, and Schema Modification
Database Design and Programming
CPSC-310 Database Systems
Chapter 5 Database Design
Chapter 6 - Database Implementation and Use
Outerjoins, Grouping/Aggregation Insert/Delete/Update
CMSC-461 Database Management Systems
Constraints and Triggers
Foreign Keys Local and Global Constraints Triggers
Database Design: DBS CB, 2nd Edition
Introduction to Database Systems, CS420
Database Construction (and Usage)
CPSC-608 Database Systems
Introduction to Database Systems, CS420
CPSC-608 Database Systems
CPSC-310 Database Systems
SQL: Constraints and Triggers
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
CPSC-608 Database Systems
CMSC-461 Database Management Systems
-Transactions in SQL -Constraints and Triggers
Assertions and Triggers
Presentation transcript:

SQL – Constraints & Triggers CS4433 Database Systems SQL – Constraints & Triggers

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 components Assertions: any SQL Boolean expression

Foreign Keys Consider Relation Movie(title, year, length, inColor, studioName, prodC#) We might expect that a studioName value is a real studio --- something appearing in Studio.name A constraint that requires a studioName in Movie to be some key in Studio is called a foreign-key constraint Expression: use the keyword REFERENCES, either: Within the declaration of an attribute, when only one attribute is involved. As an element of the schema, as: FOREIGN KEY ( <list of attributes> ) REFERENCES <relation> ( <attributes> ) Referenced attributes must be declared PRIMARY KEY or UNIQUE

Example: With Attribute CREATE TABLE Movie ( Title char(50), year int , length int, studioName int, prodC# int, PRIMARY KEY (title, year), FOREIGN KEY (studioName) REFERENCES Studio) ) CREATE TABLE Studio ( name CHAR(20), adress varchar, presC# int REFERENCES MovieExec(cert#) ); Another way for this presC# int, FOREIGN KEY (presC# )REFERENCES MovieExec(cert#));

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: An insertion or update to R introduces values not found in S A deletion or update to S causes some tuples of R to “dangle” R S

Actions Taken Suppose R = Movie, S = Studio An insert or update to Movie that introduces a nonexistent Studio must be rejected A deletion or update to Studio that removes a studio value found in some tuples of Movie can be handled in three ways Default : Reject the modification Cascade : Make the same changes in Movie Deleted studio: delete Movie tuple Updated studio: change value in Movie. NULL : Change the studioname in Movie to NULL

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] Otherwise, the default (reject) is used CREATE TABLE Movie ( Title char(50), year int , length int, studioName int, prodC# int, PRIMARY KEY (title, year), FOREIGN KEY (studioName) REFERENCES Studio) ON DELETE SET NULL ON UPDATE CASCADE);

Checks Attribute-based Check Put a constraint on the value of a particular attribute Ensure that attribute values satisfy specified condition CHECK( <condition> ) must be added 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 CREATE TABLE Movie ( Title char(50), year int CHECK ( year <= 2030) length int, studioName int CHECK (studioName IN (select name from Studio)), prodC# int, )

How is Check different from Foreign Key? The kind of conditions to enforce? The timing/actions of enforcing? An attribute-based check is checked only when a value for that attribute is inserted or updated Example: CHECK (year <= 2030) checks every new year and rejects it if it is more than 2030. Example: CHECK (studioName IN (SELECT name FROM Studio)) not checked if a studio is deleted from Studio (unlike foreign-keys)

Tuple-Based Checks CHECK ( <condition> ) may be added as another element of a schema definition 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 Example: only length of the Movie” Long Movie” can be more than 180 mins: CREATE TABLE Movie ( Title char(50), studioName int CHECK (studio name IN (select name from Studio)), prodC# int, year int CHECK ( year <= 2030) length int, CHECK (title = ’Long Movie’ OR length <= 180) );

Not null Constraint For certain attributes null values may be inappropriate Prohibit the insertion of a null value for the attribute Any other modification that would cause a null to be inserted in an attribute declared to ne nut null generates error message Student name: There can not be unknown student Declare it as; Name varchar(20) not null

Assertions CREATE ASSERTION <name> CHECK ( <condition> ); These are database-schema elements, like relations or views An assertion is a statement in SQL that ensures a certain condition will always exist in the database. Assertions are like column and table constraints, except that they are specified separately from table definitions.  Defined by: CREATE ASSERTION <name> CHECK ( <condition> ); Condition may refer to any relation or attribute in the database schema

Example create assertion recent_licenses check ( ( select count(*) from nurses where license_renewal_date < '2002-01-01' ) = 0 )

Another Example In Drinkers(name, addr, phone) and Bars(name, addr, license), there cannot be more bars than drinkers. CREATE ASSERTION FewBar CHECK ( (SELECT COUNT(*) FROM Bars) <= (SELECT COUNT(*) FROM Drinkers) );

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 Beers can affect FewBar. Neither can an insertion to Drinkers

Triggers Motivation Attribute- and tuple-based checks have limited capabilities Assertions are sufficiently general for most constraint applications, but they are hard to implement efficiently The DBMS must have real intelligence to avoid checking assertions that couldn’t possibly have been violated Solution: Trigger a procedure that starts automatically if specified changes occur to the DBMS A trigger allows the user to specify when the check occurs Like an assertion, a trigger has a general-purpose condition and also can perform any sequence of SQL database modifications

Event-Condition-Action Rules Another name for “trigger” is ECA rule, or event-condition-action rule Event : (activates the trigger) typically a type of database modification, e.g., “insert on Sells.” Condition : (tests whether the trigger should run) Any SQL Boolean-valued expression Action : (procedure executed when trigger runs) Any SQL statements Example: Instead of using a foreign-key constraint and rejecting insertions into Sells(bar, beer, price) with unknown beers, a trigger can add that beer to Beers, with a NULL manufacturer

Example: Trigger The event CREATE TRIGGER youngStudentUpdate AFTER INSERT ON Student REFERENCING NEW TABLE NewStudent FOR EACH STATEMENT INSERT INTO YoungStudent(snum, sname, major, standing, age) SELECT snum, sname, major, standing, age FROM NewStudent N WHERE N.age <= 18; apply once per statement The action

Example: Trigger Definition The event 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 condition The action

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