Assertions and Triggers in SQL

Slides:



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

Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke1 SQL: Queries, Programming, Triggers Chapter 5 Modified by Donghui Zhang.
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
Chapter 7 Notes on Foreign Keys Local and Global Constraints Triggers.
SQL: Queries, Constraints, Triggers
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke1 SQL: Queries, Constraints, Triggers Chapter 5.
SQL Constraints and Triggers
Database Management Systems, R. Ramakrishnan and J. Gehrke1 SQL: Queries, Programming, Triggers Chapter 5.
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.
Constraints and Triggers Foreign Keys Local and Global Constraints Triggers.
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,
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.
Chapter 6: Integrity Objective Key Constraints (Chapter 2) Cardinality Constraints (Chapter 2) Domain Constraints Referential Integrity Assertions Triggers.
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.
©Silberschatz, Korth and Sudarshan6.1Database System Concepts Chapter 6: Integrity and Security Domain Constraints Referential Integrity Assertions Triggers.
SCUHolliday - coen 1789–1 Schedule Today: u Constraints, assertions, triggers u Read Sections , 7.4. Next u Triggers, PL/SQL, embedded SQL, JDBC.
1 ICS 184: Introduction to Data Management Lecture Note 11: Assertions, Triggers, and Index.
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.
Advanced SQL Instructor: Mohamed Eltabakh 1 Part II.
Triggers. Why Triggers ? Suppose a warehouse wishes to maintain a minimum inventory of each item. Number of items kept in items table Items(name, number,...)
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.
IS 230Lecture 6Slide 1 Lecture 7 Advanced SQL Introduction to Database Systems IS 230 This is the instructor’s notes and student has to read the textbook.
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.
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.
Chapter 5 : Integrity And Security  Domain Constraints  Referential Integrity  Security  Triggers  Authorization  Authorization in SQL  Views 
1 SQL: Structured Query Language Chapter 5 (cont.)  Constraints  Triggers.
Database Management COP4540, SCS, FIU Database Trigger.
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.
Murali Mani Constraints. Murali Mani Keys: Primary keys and unique CREATE TABLE Student ( sNum int, sName varchar (20), dept char (2), CONSTRAINT key.
Copyright © 2004 Pearson Education, Inc.. Chapter 24 Enhanced Data Models for Advanced Applications.
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.
Chapter 6: Integrity (and Security)
SQL – Part 2.
Constraints and Triggers
Foreign Keys Local and Global Constraints Triggers
Introduction to Database Systems, CS420
SQL: Structured Query Language (‘Sequel’)
SQL: Queries, Constraints, Triggers
Advanced SQL: Views & Triggers
Instructor: Mohamed Eltabakh
Instructor: Mohamed Eltabakh
Triggers A trigger is a statement that is executed automatically by the system as a side effect of a modification to the database. To design a trigger.
SQL: Structured Query Language
SQL – Constraints & Triggers
Assertions and Triggers
Presentation transcript:

Assertions and Triggers in SQL

Assertions How to test if and FD is satisfied? ASSERTIONS: CREATE ASSERTION assertion_name CHECK predicate Example: We require that the sum of sailors and boats is smaller than 100. Here we need to specify a constraint between two tables: CREATE ASSERTION SmallClub CHECK ((SELECT COUNT(S.sid) FROM Sailors S) + (SELECT COUNT(B.bid) FROM Boats B) < 100)

Also You can do also that: CREATE TABLE Sailors( sid INTEGER, sname CHAR(10), rating INTEGER, age REAL, PRIMARY KEY (sid), CONSTRAINT smallClub CHECK( (SELECT COUNT (S.sid) FROM Sailors S) + (SELECT COUNT (B.bid) FROM Boats B) < 100 )); But it is wrong! Only checks Sailors, not Boats. Assertion is more appropriate.

Assertions Constraint: A customer with a loan should have an account with at least 1000 dollars. create assertion balance_constraint check (not exists (select * from loan L where not exists (select * from borrower B, depositor D, account A where L.loan_no = B.loan_no and B.cname = D.cname and D.account_no = A.account_no and A.balance >= 1000 ))

Another example Constraint: Customer city is always not null. customer(customer_name, customer_street, customer_city) Constraint: Customer city is always not null. Can enforce it with an assertion: Create Assertion CityCheck Check ( NOT EXISTS ( Select * From customer Where customer_city is null));

How to enforce FDs using Assertions Consider the relation: Prof(pid, pname, rank, salary) and the FD rank salary How can you enforce this? CREATE ASSERTION salary_rank CHECK ( NOT EXISTS(SELECT * FROM Prof P1, Prof P2 WHERE P1.rank = P2.rank AND P1.salary <> P2.salary))

Triggers 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 event occurs, and condition is satisfied, the action is performed.

Trigger: 3 parts Event (activates the trigger) • Condition • Action A specified modification to the DB May be an insert, deletion, or change May be limited to specific tables The trigger may fire before or after the transaction • Condition • Action Slides partially based on http://cs.gmu.edu/~jessica/cs450_s12/cs450_SQL3.pdf

Trigger: 3 parts Event • Condition(tests whether the triggers should run) – A Boolean expression or a query • If the query answer set is non-empty it evaluates to true, otherwise false • If the condition is true the trigger action occurs • Action

Trigger: 3 parts Event • Condition • Action – A trigger's action can be very far-ranging, e.g. • Execute queries • Make modifications to the DB • Create new tables • Call host-language procedures

When and how many times Synchronization of the Trigger with the activating statement (DB modification) – Before – After • Number of Activations of the Trigger – Once per modified tuple (FOR EACH ROW) – Once per activating statement (FOR EACH STATEMENT)

Two different levels Statement-level trigger: executed once for all the tuples that are changed in one SQL statement. REFERENCING NEW TABLE AS newtuples, OLD TABLE AS oldtuples • Row-level trigger: executed once for each modified tuple. REFERENCING OLD AS oldtuple, NEW AS newtuple newtuples, oldtuples, newtuple oldtuples can be used in the CONDITION and ACTION clauses The action of a trigger can consist of multiple SQL statements, surrounded by BEGIN . . . END.

Examples (in Oracle): CREATE TRIGGER youngSailorUpdate AFTER INSERT ON SAILORS /* Event */ REFERENCING NEW TABLE NewSailors FOR EACH STATEMENT INSERT /* Action */ INTO YoungSailors(sid, name, age, rating) SELECT sid, name, age, rating FROM NewSailors N WHERE N.age <= 18; • This trigger inserts young sailors into a separate table. • It has no (i.e., an empty, always true) condition.

Another Example CREATE TRIGGER notTooManyReservations AFTER INSERT ON Reserves /* Event */ REFERENCING NEW ROW NewReservation FOR EACH ROW WHEN (10 <= (SELECT COUNT(*) FROM Reserves WHERE sid =NewReservation.sid)) /* Condition */ DELETE FROM Reserves R WHERE R.sid= NewReservation.sid /* Action */ AND day= (SELECT MIN(day) FROM Reserves R2 WHERE R2.sid=R.sid); • This trigger makes sure that a sailor has less than 10 reservations, deleting the oldest reservation of a given sailor, if neccesary. • It has a non- empty condition (WHEN).

Another Example 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 >= 60000

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

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

Example Trigger CREATE TRIGGER minSalary BEFORE INSERT ON Professor FOR EACH ROW BEGIN IF (:new.salary < 60000) THEN RAISE_APPLICATION_ERROR (-20004,‘Violation of Minimum Professor Salary’); END IF; END; (Oracle example. In Postgres use RAISE EXCEPTION)

Example trigger CREATE TRIGGER minSalary BEFORE INSERT ON Professor FOR EACH ROW DECLARE temp int; -- dummy variable not needed BEGIN IF (:new.salary < 60000) THEN RAISE_APPLICATION_ERROR (-20004,‘Violation of Minimum Professor Salary’); END IF; temp := 10; -- to illustrate declared variables END; .

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.

Example: Statement level trigger CREATE TRIGGER MYTRIG1 BEFORE INSERT ON Account FOR EACH STATEMENT --- is default 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;

When to use BEFORE/AFTER Based on efficiency considerations or semantics. 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 !!

Syntax of creating a Trigger CREATE TRIGGER <triggerName> BEFORE|AFTER INSERT|DELETE|UPDATE [OF <columnList>] ON <tableName>|<viewName> [REFERENCING [OLD AS <oldName>] [NEW AS <newName>]] [FOR EACH ROW] (default is “FOR EACH STATEMENT”) [WHEN (<condition>)] <PSM body>; Syntax in PostgreSQL: http://www.postgresql.org/docs/9.4/static/sql-createtrigger.html