1 SQL: Structured Query Language Chapter 5 (cont.)  Constraints  Triggers.

Slides:



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

Database Management Systems, R. Ramakrishnan and J. Gehrke1 The Relational Model Chapter 3.
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke1 SQL: Queries, Programming, Triggers Chapter 5 Modified by Donghui Zhang.
The Relational Model. Introduction Introduced by Ted Codd at IBM Research in 1970 The relational model represents data in the form of table. Main concept.
Database Management System Module 3:. Complex Constraints In this we specify complex integrity constraints included in SQL. It relates to integrity constraints.
IC and Triggers in SQL. Find age of the youngest sailor with age
1 Lecture 11: Basic SQL, Integrity constraints
SQL: Queries, Constraints, Triggers
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke1 SQL: Queries, Constraints, Triggers Chapter 5.
Database Management Systems 1 Raghu Ramakrishnan SQL: Queries, Programming, Triggers Chpt 5.
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),
Database Management Systems, R. Ramakrishnan and J. Gehrke1 SQL: Queries, Programming, Triggers Chapter 5.
Triggers The different types of integrity constraints discussed so far provide a declarative mechanism to associate “simple” conditions with a table such.
SQL 2 – The Sequel R&G, Chapter 5 Lecture 10. Administrivia Homework 2 assignment now available –Due a week from Sunday Midterm exam will be evening of.
SPRING 2004CENG 3521 SQL: Constraints, Triggers, Embedded SQL Chapters: 5, 6.
Rutgers University SQL: Queries, Constraints, Triggers 198:541 Rutgers University.
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.
1 SQL: Structured Query Language (‘Sequel’) Chapter 5 (cont.)
Cs3431 Triggers vs Constraints Section 7.5. cs3431 Triggers (Make DB Active) Trigger: A procedure that starts automatically if specified changes occur.
CMPT 354, Simon Fraser University, Fall 2008, Martin Ester 157 Database Systems I SQL Constraints and Triggers.
CSC343 – Introduction to Databases - A. Vaisman1 SQL: Queries, Programming, Triggers.
Chapter 7 Constraints and Triggers Spring 2011 Instructor: Hassan Khosravi.
Review Three things managed by a DBMS 1.Data organization  E/R Model  Relational Model 2.Data Retrieval  Relational Algebra  SQL 3.Data Integrity.
Chapter 6: Integrity and Security Thomas Nikl 19 October, 2004 CS157B.
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 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.
1 SQL: Constraints and Triggers Chapter 5,
Unit 5/COMP3300/ SQL: Queries, Programming, Triggers Chapter 5.
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke1 SQL: Queries, Constraints, Triggers Chapter 5.
SQL: Queries, Programming, Triggers. Example Instances We will use these instances of the Sailors and Reserves relations in our examples. If the key for.
ICS 321 Fall 2011 Constraints, Triggers, Views & Indexes Asst. Prof. Lipyeow Lim Information & Computer Science Department University of Hawaii at Manoa.
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke1 SQL: Constraints and Triggers Chapter 5,
Constraints, Triggers and Views COMSATS INSTITUTE OF INFORMATION TECHNOLOGY, VEHARI.
SQL Integrity Constraints. 421B: Database Systems - Integrity Constraints 2 Integrity Constraints (Review) q An IC describes conditions that every legal.
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.
Constraints and Triggers. What’s IC? Integrity Constraints define the valid states of SQL-data by constraining the values in the base tables. –Restrictions.
PL/SQLPL/SQL Oracle10g Developer: PL/SQL Programming Chapter 9 Database Triggers.
Advanced SQL Concepts - Checking of Constraints CIS 4301 Lecture Notes Lecture /6/2006.
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke1 SQL: Queries, Constraints, Triggers Chapter 5.
1 SQL: Queries, Constraints, Triggers Chapter 5. 2 Overview: Features of SQL  Data definition language: used to create, destroy, and modify tables and.
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke1 Database Management Systems Chapter 5 SQL.
CS34311 The Relational Model. cs34312 Why Relational Model? Currently the most widely used Vendors: Oracle, Microsoft, IBM Older models still used IBM’s.
Assertions and Triggers in SQL
Database Management COP4540, SCS, FIU Database Trigger.
Constraints and Views Chap. 3-5 continued (7 th ed. 5-7)
Murali Mani Constraints. Murali Mani Keys: Primary keys and unique CREATE TABLE Student ( sNum int, sName varchar (20), dept char (2), CONSTRAINT key.
Chapter 3 The Relational Model. Why Study the Relational Model? Most widely used model. Vendors: IBM, Informix, Microsoft, Oracle, Sybase, etc. “Legacy.
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.
SQL – Part 2.
Creating Database Triggers
Constraints and Triggers
SQL Stored Triggers Presented by: Dr. Samir Tartir
SQL: Structured Query Language (‘Sequel’)
Advanced SQL: Views & Triggers
Instructor: Mohamed Eltabakh
Instructor: Mohamed Eltabakh
SQL: Queries, Programming, Triggers
SQL: Structured Query Language
SQL – Constraints & Triggers
Presentation transcript:

1 SQL: Structured Query Language Chapter 5 (cont.)  Constraints  Triggers

2 Integrity Constraints  Constraint describes conditions that every legal instance of a relation must satisfy.  Inserts/deletes/updates that violate ICs are disallowed.  Can be used to : ensure application semantics e.g., sid is a key prevent inconsistencies e.g., sname has to be a string, age must be < 200;

3 Types of Integrity Constraints  Fundamental: Domain constraints, Primary key constraints, Foreign key constraints Plus, NOT NULL, UNIQUE.  General: Check constraints Table constraints (assertions)

4 Check or Table Constraints  Can use queries to express constraint. CREATE TABLE Sailors ( sid INTEGER, sname CHAR(10), rating INTEGER, age REAL, PRIMARY KEY (sid), CHECK ( rating >= 1 AND rating <= 10 ))

5 Explicit Domain Constraints CREATE TABLE Sailors ( sid INTEGER, sname CHAR(10), rating values-of-ratings, age REAL, PRIMARY KEY (sid)) CREATE DOMAIN values-of-ratings INTEGER DEFAULT 1 CHECK ( VALUE >= 1 AND VALUE <= 10)

6 More Powerful Table Constraints CREATE TABLE Reserves ( sname CHAR(10), bid INTEGER, day DATE, PRIMARY KEY (bid,day), CONSTRAINT noInterlakeRes CHECK (`Interlake’ <> ( SELECT B.bname FROM Boats B WHERE B.bid= bid)))  Constraint that Interlake boats cannot be reserved:  If condition evaluates to FALSE, update is rejected.

7 Table Constraints  Associated with one table  Only needs to hold TRUE when table is non-empty.

8 Table Constraints with Complex CHECK CREATE TABLE Sailors ( sid INTEGER, sname CHAR(10), rating INTEGER, age REAL, PRIMARY KEY (sid), CHECK ( (SELECT COUNT (S.sid) FROM Sailors S) + (SELECT COUNT (B.bid) FROM Boats B) < 100 )  Symmetric constraint, yet associated with Sailors.  If Sailors is empty, the number of Boats tuples can be anything! Number of boats plus number of sailors is < 100

9 Assertions: Constraints over Multiple Relations CREATE TABLE Sailors ( sid INTEGER, sname CHAR(10), rating INTEGER, age REAL, PRIMARY KEY (sid), )  ASSERTION not associated with either table. CREATE ASSERTION smallClub CHECK ( (SELECT COUNT (S.sid) FROM Sailors S) + (SELECT COUNT (B.bid) FROM Boats B) < 100 ) Number of boats plus number of sailors is < 100

10 Triggers (Active database)  Trigger: A procedure that starts automatically if specified changes occur to the DBMS  Analog to a "daemon" that monitors a database for certain events to occur  Three parts:  Event (activates the trigger)  Condition (tests whether the triggers should run) [Optional]  Action (what happens if the trigger runs)  Semantics:  When an event occurs,  And this condition is satisfied,  Then the associated action is performed.

11 Triggers – Event,Condition,Action  Events could be : BEFORE|AFTER INSERT|UPDATE|DELETE ON e.g.: BEFORE INSERT ON Professor  Condition is SQL expression that or even an SQL query (A query with a non-empty result means TRUE)  Action can be many different choices :  SQL statements, body of PSM, and even DDL and transaction-oriented statements like “commit”.

12 Example Trigger Assume our DB has a relation schema : Professor (pNum, pName, salary) We want to write a trigger that : Ensures that any new professor inserted has salary >= 90000

13 Example Trigger CREATE TRIGGER minSalary BEFORE INSERT ON Professor for what context ? BEGIN check for violation here ? END;

14 Example Trigger CREATE TRIGGER minSalary BEFORE INSERT ON Professor FOR EACH ROW BEGIN Violation of Minimum Professor Salary? END;

15 Example Trigger CREATE TRIGGER minSalary BEFORE INSERT ON Professor FOR EACH ROW BEGIN IF (:new.salary < 90000) THEN RAISE_APPLICATION_ERROR (-20004, ‘Violation of Minimum Professor Salary’); END IF; END;

16 Example trigger CREATE TRIGGER minSalary BEFORE INSERT ON Professor FOR EACH ROW DECLARE temp int; -- dummy variable not needed BEGIN IF (:new.salary < 90000) THEN RAISE_APPLICATION_ERROR (-20004, ‘Violation of Minimum Professor Salary’); END IF; temp := 10;-- to illustrate declared variables END;. Note: In SQLPLUS, don’t forget the “dot” after the trigger.

17 Details of Trigger Example  BEFORE INSERT ON Professor  This trigger is checked before the tuple is inserted  FOR EACH ROW  specifies that trigger is performed for each row inserted  :new  refers to the new tuple inserted  If (:new.salary < 90000)  then an application error is raised and hence the row is not inserted; otherwise the row is inserted.  Use error code: ;  this is invalid range

18 Example Trigger Using Condition CREATE TRIGGER minSalary BEFORE INSERT ON Professor FOR EACH ROW WHEN (new.salary < 90000) BEGIN RAISE_APPLICATION_ERROR (-20004, ‘Violation of Minimum Professor Salary’); END;  Conditions can refer to old/new values of tuples modified by the statement activating the trigger.

19 Triggers: REFERENCING CREATE TRIGGER minSalary BEFORE INSERT ON Professor REFERENCING NEW as newTuple FOR EACH ROW WHEN (newTuple.salary < 90000) BEGIN RAISE_APPLICATION_ERROR (-20004, ‘Violation of Minimum Professor Salary’); END;

20 Example Trigger CREATE TRIGGER minSalary BEFORE UPDATE ON Professor REFERENCING OLD AS oldTuple NEW as newTuple FOR EACH ROW WHEN (newTuple.salary < oldTuple.salary) BEGIN RAISE_APPLICATION_ERROR (-20004, ‘Salary Decreasing !!’); END;  Ensure that salary does not decrease

21 Another Trigger Example (SQL:99) CREATE TRIGGER youngSailorUpdate AFTER INSERT ON SAILORS REFERENCING NEW TABLE AS NewSailors FOR EACH STATEMENT INSERT INTO YoungSailors(sid, name, age, rating) SELECT sid, name, age, rating FROM NewSailors N WHERE N.age <= 18

22 Row vs Statement Level Trigger  Row level: activated once per modified tuple  Statement level: activate once per SQL statement  Row level triggers can access new data, statement level triggers cannot generally do that (depends on DBMS).  Statement level triggers will be more efficient if we do not need to make row-specific decisions

23 Row vs Statement Level Trigger  Example: Consider a relation schema : Account (num, amount) where we will allow creation of new accounts only during normal business hours.

24 Example: Statement level trigger CREATE TRIGGER MYTRIG1 BEFORE INSERT ON Account FOR EACH STATEMENT BEGIN IF (TO_CHAR(SYSDATE,’dy’) IN (‘sat’,’sun’)) OR (TO_CHAR(SYSDATE,’hh24:mi’) NOT BETWEEN ’08:00’ AND ’17:00’) THEN RAISE_APPLICATION_ERROR(-20500,’Cannot create new account now !!’); END IF; END; Note: “FOR EACH STATEMENT” is default; so in some systems you omit this clause!

25 Another Trigger Example (SQL:99) CREATE TRIGGER youngSailorUpdate AFTER INSERT ON SAILORS REFERENCING NEW TABLE AS NewSailors FOR EACH STATEMENT INSERT INTO YoungSailors(sid, name, age, rating) SELECT sid, name, age, rating FROM NewSailors N WHERE N.age <= 18 Note: Oracle uses “ FOR EACH STATEMENT” as default, hence you would simply not list this. They also do not support reference to such a delta-table as above.

26 When to use BEFORE/AFTER  Based on semantics and also on efficiency considerations.  Suppose we perform statement-level after insert, then all the rows are inserted first, then if the condition fails, and all the inserted rows must be “rolled back”  Not very efficient !!

27 Combining multiple events into one trigger CREATE TRIGGER salaryRestrictions AFTER INSERT OR UPDATE ON Professor FOR EACH ROW BEGIN IF (INSERTING AND :new.salary < 90000) THEN RAISE_APPLICATION_ERROR (-20004, 'below min salary'); END IF; IF (UPDATING AND :new.salary < :old.salary) THEN RAISE_APPLICATION_ERROR (-20004, ‘Salary Decreasing !!'); END IF; END;

28 Summary : Trigger Syntax CREATE TRIGGER BEFORE|AFTER INSERT|DELETE|UPDATE [OF ] ON | [REFERENCING [OLD AS ] [NEW AS ]] [FOR EACH ROW] (default is “FOR EACH STATEMENT”) [WHEN ( )] ;

29 Some Points about Triggers  Check the system tables :  user_triggers  user_trigger_cols  ORA : mutating relation problem  In a row level trigger, you cannot have the body refer to the table specified in the event  Also INSTEAD OF triggers can be specified on views

30 Some Points about Triggers  Check the system tables :  user_triggers  user_trigger_cols  ORA : mutating relation problem  In a row level trigger, you cannot have the body refer to the table specified in the event  Also INSTEAD OF triggers can be specified on views

31 Some Points about Triggers  Check the system tables :  user_triggers  user_trigger_cols  ORA : mutating relation problem  In a row level trigger, you cannot have the body refer to the table specified in the event  Also INSTEAD OF triggers can be specified on views

32 Triggers and Oracle Note 1: Running Triggers. End CREATE TRIGGER statement with a dot and run:  Type the body of the trigger  Press '.' to terminate the sql statement  Type 'run' to create the trigger Example: > CREATE TRIGGER minSalary BEFORE …. …. END;. > run;  Running the CREATE TRIGGER statement only creates the trigger; it does not execute it.  Only a triggering event, such as an insertion, causes the trigger to execute.

33 Triggers and Oracle  Note 2: Displaying Trigger Definition Errors If you get compilation errors, you can see the error messages by typing in:  show errors trigger ; Example: > show errors trigger minSalary; However, the reported line numbers where the errors occur are not always accurate.

34 Constraints versus Triggers  Constraints are useful for database consistency  Use IC when sufficient  More opportunity for optimization  Not restricted into insert/delete/update  Triggers are flexible and powerful  Alerters  Event logging for auditing  Security enforcement  Analysis of table accesses (statistics)  Workflow and business intelligence …  But can be hard to understand ……  Several triggers (Arbitrary order  unpredictable !?)  Chain triggers (When to stop ?)  Recursive triggers (Termination?)

35 Summary  SQL allows specification of rich integrity constraints and their efficient maintenance  Triggers respond to changes in the database: powerful for enforcing application semantics