Advanced SQL: Triggers & Assertions

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

PL/SQL.
1 Constraints, Triggers and Active Databases Chapter 9.
Database Management Systems, R. Ramakrishnan and J. Gehrke1 The Relational Model Chapter 3.
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),
Triggers The different types of integrity constraints discussed so far provide a declarative mechanism to associate “simple” conditions with a table such.
SPRING 2004CENG 3521 The Relational Model Chapter 3.
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.)
Database Systems More SQL Database Design -- More SQL1.
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.
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.
PL / SQL P rocedural L anguage / S tructured Q uery L anguage Chapter 7 in Lab Reference.
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.
CSE314 Database Systems More SQL: Complex Queries, Triggers, Views, and Schema Modification Doç. Dr. Mehmet Göktürk src: Elmasri & Navanthe 6E Pearson.
1 The Relational Model Instructor: Mohamed Eltabakh
1 ICS 184: Introduction to Data Management Lecture Note 11: Assertions, Triggers, and Index.
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,
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.
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.
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.
Objectives Database triggers and syntax
Module Coordinator Tan Szu Tak School of Information and Communication Technology, Politeknik Brunei Semester
PL/SQLPL/SQL Oracle10g Developer: PL/SQL Programming Chapter 9 Database Triggers.
PL/SQLPL/SQL Oracle11g: PL/SQL Programming Chapter 9 Database Triggers.
Chapter 5 : Integrity And Security  Domain Constraints  Referential Integrity  Security  Triggers  Authorization  Authorization in SQL  Views 
Professor: Dr. Shu-Ching Chen TA: Hsin-Yu Ha Function, Trigger used in PosgreSQL.
1 SQL: Structured Query Language Chapter 5 (cont.)  Constraints  Triggers.
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.
Advanced SQL: Cursors & Stored Procedures Instructor: Mohamed Eltabakh 1.
Relational Algebra Instructor: Mohamed Eltabakh 1.
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.
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.
Copyright © 2004 Pearson Education, Inc.. Chapter 24 Enhanced Data Models for Advanced Applications.
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.
More SQL: Complex Queries, Triggers, Views, and Schema Modification
Chapter 6: Integrity (and Security)
Creating Database Triggers
Constraints and Triggers
SQL Stored Triggers Presented by: Dr. Samir Tartir
Introduction to Database Systems, CS420
Advanced SQL: Views & Triggers
Instructor: Mohamed Eltabakh
Instructor: Mohamed Eltabakh
SQL: Structured Query Language
SQL: Structured Query Language
SQL: Structured Query Language
Presentation transcript:

Advanced SQL: Triggers & Assertions Instructor: Mohamed Eltabakh meltabakh@cs.wpi.edu

Today’s Roadmap Views Triggers Assertions Cursors Stored Procedures We covered these To be covered today

Views’ Recap An SQL query that we register (store) inside the database No Data are stored in the database (only the definition) Any query can be a view View name CREATE VIEW ProfNumStudents AS SELECT pNumber, count(*) AS CNT FROM Student GROUP BY pNumber; View schema (pNumber, CNT)

Views’ Recap (Cont’d) Query a view as any regular table CREATE VIEW ProfNumStudents AS SELECT pNumber, count(*) AS CNT FROM Student GROUP BY pNumber; Create the view Query: Select the professor number who has more that 20 students Query the view Select pNumber From ProfNumStudents Where CNT > 20;

Triggers

Triggers: Introduction The application constraints need to be captured inside the database Some constraints can be captured by: Primary Keys, Foreign Keys, Unique, Not NULL, and domain constraints CREATE TABLE Students (sid: CHAR(20), name: CHAR(20) NOT NULL, login: CHAR(10), age: INTEGER, gpa: REAL Default 0, Constraint pk Primary Key (sid), Constraint u1 Unique (login), Constraint gpaMax check (gpa <= 4.0) ); These constraints are defined in CREATE TABLE or ALTER TABLE

Triggers: Introduction Some application constraints are complex Need for assertions and triggers Examples: Sum of loans taken by a customer does not exceed 100,000 Student cannot take the same course after getting a pass grade in it Age field is derived automatically from the Date-of-Birth field

Lets see how to define these components Trigger Components Three components Event: When this event happens, the trigger is activated Condition (optional): If the condition is true, the trigger executes, otherwise skipped Action: The actions performed by the trigger Semantics When the Event occurs and Condition is true, execute the Action Lets see how to define these components

Trigger: Events Three event types Two triggering times Insert Update Delete Two triggering times Before the event After the event Two granularities Execute for each row Execute for each statement

1) Trigger: Event Example Trigger name That is the event Create Trigger <name> Before|After Insert|Update|Delete ON <tablename> …. That is the event Example Create Trigger ABC Before Insert On Students …. This trigger is activated when an insert statement is issued, but before the new record is inserted Create Trigger XYZ After Update On Students …. This trigger is activated when an update statement is issued and after the update is executed

Granularity of Event A single SQL statement may update, delete, or insert many records at the same time E.g., Update student set gpa = gpa x 0.8; Does the trigger execute for each updated or deleted record, or once for the entire statement ? We define such granularity Create Trigger <name> Before| After Insert| Update| Delete For Each Row | For Each Statement …. This is the event This is the granularity

Example: Granularity of Event Create Trigger XYZ After Update ON <tablename> For each statement …. This trigger is activated once (per UPDATE statement) after all records are updated Create Trigger XYZ Before Delete ON <tablename> For each row …. This trigger is activated before deleting each record

2) Trigger: Condition This component is optional Trigger executes only if the condition is true Create Trigger <name> Before| After Insert| Update| Delete On <tableName> For Each Row | For Each Statement When <condition> … That is the condition If the employee salary > 150,000 then some actions will be taken Create Trigger EmpSal After Insert or Update On Employee For Each Row When (new.salary >150,000) …

3) Trigger: Action Action depends on what you want to do, e.g.: Check certain values Fill in some values Inserts/deletes/updates other records Check that some business constraints are satisfied Commit (approve the transaction) or roll back (cancel the transaction) In the action, you may want to reference: The new values of inserted or updated records (:new) The old values of deleted or updated records (:old)

Trigger: Referencing Values In the action, you may want to reference: The new values of inserted or updated records (:new) The old values of deleted or updated records (:old) Create Trigger EmpSal After Insert or Update On Employee For Each Row When (new.salary >150,000) Begin if (:new.salary < 100,000) … End; Inside “When”, the “new” and “old” should not have “:” Trigger body Inside the trigger body, they should have “:”

Trigger: Referencing Values (Cont’d) Insert Event Has only :new defined Delete Event Has only :old defined Update Event Has both :new and :old defined Before triggering (for insert/update) Can update the values in :new Changing :old values does not make sense After triggering Should not change :new because the event is already done

Example 1 If the employee salary increased by more than 10%, make sure the ‘rank’ field is not empty and its value has changed, otherwise reject the update If the trigger exists, then drop it first Create or Replace Trigger EmpSal Before Update On Employee For Each Row Begin IF (:new.salary > (:old.salary * 1.1)) Then IF (:new.rank is null or :new.rank = :old.rank) Then RAISE_APPLICATION_ERROR(-20004, 'rank field not correct'); End IF; End; / Compare the old and new salaries Make sure to have the “/” to run the command

Example 2 If the employee salary increased by more than 10%, then increment the rank field by 1. In the case of Update event only, we can specify which columns Create or Replace Trigger EmpSal Before Update Of salary On Employee For Each Row Begin IF (:new.salary > (:old.salary * 1.1)) Then :new.rank := :old.rank + 1; End IF; End; / We changed the new value of rank field The assignment operator has “:”

Example 3: Using Temp Variable If the newly inserted record in employee has null hireDate field, fill it in with the current date Since we need to change values, then it must be “Before” event Create Trigger EmpDate Before Insert On Employee For Each Row Declare temp date; Begin Select sysdate into temp from dual; IF (:new.hireDate is null) Then :new.hireDate := temp; End IF; End; / Declare section to define variables Oracle way to select the current date Updating the new value of hireDate before inserting it

Example 4: Maintenance of Derived Attributes Keep the bonus attribute in Employee table always 3% of the salary attribute Indicate two events at the same time Create Trigger EmpBonus Before Insert Or Update On Employee For Each Row Begin :new.bonus := :new.salary * 0.03; End; / The bonus value is always computed automatically

Combining Multiple Events in One Trigger If you combine multiple operations Sometimes you need to know what is the current operation Create Trigger EmpBonus Before Insert Or Update On Employee For Each Row Begin IF (inserting) Then … End IF; IF (updating) Then … End IF; End; / Combine Insert and Update Can do something different under each operation

Before vs. After Before Event After Event When checking certain conditions that may cause the operation to be cancelled E.g., if the name is null, do not insert When modifying values before the operation E.g., if the date is null, put the current date After Event When taking other actions that will not affect the current operations The insert in table X will cause an update in table Y Before Insert Trigger: :new.x := …. //Changing value x that will be inserted After Insert Trigger: :new.x := … //meaningless because the value is already inserted

Row-Level vs. Statement-Level Triggers Example: Update emp set salary = 1.1 * salary; Changes many rows (records) Row-level triggers Check individual values and can update them Have access to :new and :old vectors Statement-level triggers Do not have access to :new or :old vectors (only for row-level) Execute once for the entire statement regardless how many records are affected Used for verification before or after the statement

Example 5: Statement-level Trigger Store the count of employees having salary > 100,000 in table R Indicate three events at the same time Create Trigger EmpBonus After Insert Or Update of salary Or Delete On Employee For Each Statement Begin delete from R; insert into R(cnt) Select count(*) from employee where salary > 100,000; End; / Delete the existing record in R, and then insert the new count.

Order Of Trigger Firing Loop over each affected record Before Trigger (statement-level) Before Trigger (row-level) Event (row-level) After Trigger (row-level) After Trigger (statement-level)

Some Other Operations Dropping Trigger If creating trigger with errors SQL> Drop Trigger <trigger name>; SQL > Show errors; It displays the compilation errors

Key Points in Triggers Must understand what type of trigger to create Before or After Under which operation: Insert, Update, or Delete Row-level or Statement-level :old and :new variables Update  both are available Insert  Only :new is available Delete  Only :old is available

Assertions

Assertions An expression that should be always true When created, the expression must be true DBMS checks the assertion after any change that may violate the expression Must return True or False

Sum of loans taken by a customer does not exceed 100,000 Example 1 Sum of loans taken by a customer does not exceed 100,000 Must return True or False (not a relation) Create Assertion SumLoans Check ( 100,000 >= ALL Select Sum(amount) From borrower B , loan L Where B.loan_number = L.loan_number Group By customer_name );

Number of accounts for each customer in a given branch is at most two Example 2 Number of accounts for each customer in a given branch is at most two Create Assertion NumAccounts Check ( 2 >= ALL Select count(*) From account A , depositor D Where A.account_number = D.account_number Group By customer_name, branch_name );

Customer city is always not null Example 3 Customer city is always not null Create Assertion CityCheck Check ( NOT EXISTS ( Select * From customer Where customer_city is null));

Assertions vs. Triggers Assertions do not modify the data, they only check certain conditions Triggers are more powerful because the can check conditions and also modify the data Assertions are not linked to specific tables in the database and not linked to specific events Triggers are linked to specific tables and specific events

Assertions vs. Triggers (Cont’d) All assertions can be implemented as triggers (one or more) Not all triggers can be implemented as assertions Oracle does not have assertions

Example: Trigger vs. Assertion All new customers opening an account must have opening balance >= $100. However, once the account is opened their balance can fall below that amount. We need triggers, assertions cannot be used Trigger Event: Before Insert Create Trigger OpeningBal Before Insert On Customer For Each Row Begin IF (:new.balance is null or :new.balance < 100) Then RAISE_APPLICATION_ERROR(-20004, 'Balance should be >= $100'); End IF; End;

Triggers & Assertions Any Questions