Announcements (September 21) SQL: Part III. Triggers. Active data. Trigger options. Trigger example

Similar documents
SQL: Part III. Announcements. Constraints. CPS 216 Advanced Database Systems

EECS 647: Introduction to Database Systems

SQL: Triggers, Views, Indexes. Introduction to Databases CompSci 316 Fall 2018

SQL: Part II. Announcements (September 18) Incomplete information. CPS 116 Introduction to Database Systems. Homework #1 due today (11:59pm)

Announcements (September 18) SQL: Part II. Solution 1. Incomplete information. Solution 3? Solution 2. Homework #1 due today (11:59pm)

Announcements (September 14) SQL: Part I SQL. Creating and dropping tables. Basic queries: SFW statement. Example: reading a table

Relational Model & Algebra. Announcements (Thu. Aug. 27) Relational data model. CPS 116 Introduction to Database Systems

Announcements. Relational Model & Algebra. Example. Relational data model. Example. Schema versus instance. Lecture notes

Relational Model & Algebra. Announcements (Tue. Sep. 3) Relational data model. CompSci 316 Introduction to Database Systems

What s a database system? Review of Basic Database Concepts. Entity-relationship (E/R) diagram. Two important questions. Physical data independence

Query Processing: A Systems View. Announcements (March 1) Physical (execution) plan. CPS 216 Advanced Database Systems

DATA AND SCHEMA MODIFICATIONS CHAPTERS 4,5 (6/E) CHAPTER 8 (5/E)

Database Management Systems Triggers

SQL: Transactions. Announcements (October 2) Transactions. CPS 116 Introduction to Database Systems. Project milestone #1 due in 1½ weeks

Announcements (March 1) Query Processing: A Systems View. Physical (execution) plan. Announcements (March 3) Physical plan execution

Integrity Constraints (Reminder)

Database Applications (15-415)

Introduction to Data Management. Lecture #4 (E-R Relational Translation)

Relational Database Design Part I. Announcement. Relational model: review. CPS 116 Introduction to Database Systems

Announcements (January 20) Relational Database Design. Database (schema) design. Entity-relationship (E/R) model. ODL (Object Definition Language)

The Relational Model. Week 2

The Relational Model. Chapter 3. Comp 521 Files and Databases Fall

Today's Class. Carnegie Mellon Univ. Dept. of Computer Science /615 - DB Applications. Example Database. Query Plan Example

SQL: Programming Midterm in class next Thursday (October 5)

The Relational Model 2. Week 3

EECS 647: Introduction to Database Systems

Asst. Prof. Lipyeow Lim Information & Computer Science Department University of Hawaii at Manoa

SQL: Programming. Announcements (September 25) Motivation. CPS 116 Introduction to Database Systems. Pros and cons of SQL.

Chapter 7 Constraints and Triggers. Spring 2011 Instructor: Hassan Khosravi

The Relational Data Model. Data Model

Plan for today. Query Processing/Optimization. Parsing. A query s trip through the DBMS. Validation. Logical plan

CMPT 354: Database System I. Lecture 3. SQL Basics

Basic operators: selection, projection, cross product, union, difference,

CS 464/564 Introduction to Database Management System Instructor: Abdullah Mueen

EECS 647: Introduction to Database Systems

The Relational Model. Relational Data Model Relational Query Language (DDL + DML) Integrity Constraints (IC)

The Relational Model. Chapter 3. Comp 521 Files and Databases Fall

Comp 5311 Database Management Systems. 4b. Structured Query Language 3

EECS 647: Introduction to Database Systems

Lecture 2: Introduction to SQL

Introduction to Data Management. Lecture #4 (E-R à Relational Design)

Relational Database Design Part I. Announcements (September 5) Relational model: review. CPS 116 Introduction to Database Systems

Lecture 2 SQL. Instructor: Sudeepa Roy. CompSci 516: Data Intensive Computing Systems

Constraints, Views & Indexes. Running Example. Kinds of Constraints INTEGRITY CONSTRAINTS. Keys Foreign key or referential integrity constraints

Database Management Systems. Chapter 3 Part 1

Lesson 14 Transcript: Triggers

Database Systems ( 資料庫系統 )

Announcements. SQL: Part IV. Transactions. Summary of SQL features covered so far. Fine prints. SQL transactions. Reading assignments for this week

Carnegie Mellon Univ. Dept. of Computer Science /615 - DB Applications. Today's Party. Example Database. Faloutsos/Pavlo CMU /615

Database Management System Dr. S. Srinath Department of Computer Science & Engineering Indian Institute of Technology, Madras Lecture No.

Relational Database Design. Announcements. Database (schema) design. CPS 216 Advanced Database Systems. DB2 accounts have been set up

Chapter 7: Constraints and Triggers. Foreign Keys Local and Global Constraints Triggers

The Relational Model. Chapter 3

Introduction to SQL Part 1 By Michael Hahsler based on slides for CS145 Introduction to Databases (Stanford)

COMP 244 DATABASE CONCEPTS & APPLICATIONS

Relational Model. Topics. Relational Model. Why Study the Relational Model? Linda Wu (CMPT )

NULL. The special value NULL could mean: Unknown Unavailable Not Applicable

CSEN 501 CSEN501 - Databases I

Triggers- View-Sequence

Introduction to Data Management. Lecture #5 Relational Model (Cont.) & E-Rà Relational Mapping

The Relational Model. Chapter 3. Database Management Systems, R. Ramakrishnan and J. Gehrke 1

Relational data model

Relational Model and Algebra. Introduction to Databases CompSci 316 Fall 2018

EGCI 321: Database Systems. Dr. Tanasanee Phienthrakul

The Relational Model of Data (ii)

Indexing. Announcements. Basics. CPS 116 Introduction to Database Systems

Constraints. Local and Global Constraints Triggers

Announcement. Relational Database Design Part I. Keys. Relational model: review. Schema vs. data. More examples of keys

SQL: Part II. Introduction to Databases CompSci 316 Fall 2018

Introduction to Data Management CSE 344

SQL: Queries, Constraints, Triggers (iii)

Introduction to Data Management. Lecture 16 (SQL: There s STILL More...) It s time for another installment of...

Topics to Learn. Important concepts. Tree-based index. Hash-based index

Data Modelling and Databases. Exercise Session 7: Integrity Constraints

Introduction to Data Management. Lecture #1 (The Course Trailer )

Optimization Overview

The Relational Model

Introduction to Data Management. Lecture #17 (SQL, the Never Ending Story )

Introduction to Database Systems CSE 414

Introduction to Data Management. Lecture #1 (Course Trailer ) Instructor: Chen Li

Relational Model and Relational Algebra

Chapter 14. Active Databases. Database Systems(Part 2) p. 200/286

SQL DATA DEFINITION LANGUAGE

Where Are We? Next Few Lectures. Integrity Constraints Motivation. Constraints in E/R Diagrams. Keys in E/R Diagrams

Databases 1. Defining Tables, Constraints

Modern Database Systems CS-E4610

Administrivia. The Relational Model. Review. Review. Review. Some useful terms

Lecture 16. The Relational Model

CS143: Index. Book Chapters: (4 th ) , (5 th ) , , 12.10

Introduction to Data Management. Lecture #1 (Course Trailer )

Constraints. Primary Key Foreign Key General table constraints Domain constraints Assertions Triggers. John Edgar 2

Database Management Systems. Chapter 5

Annoucements. Where are we now? Today. A motivating example. Recursion! Lecture 21 Recursive Query Evaluation and Datalog Instructor: Sudeepa Roy

CSC 261/461 Database Systems Lecture 19

Database Systems. Course Administration

The Relational Model

CS425 Midterm Exam Summer C 2012

CS143: Relational Model

Lecture 3: SQL Part II

L22: The Relational Model (continued) CS3200 Database design (sp18 s2) 4/5/2018

Transcription:

Announcements (September 21) 2 SQL: Part III CPS 116 Introduction to Database Systems Homework #2 due next Thursday Homework #1 sample solution available today Hardcopies only Check the handout box outside my office if you did not pick one up during the lecture Project milestone #1 due in 3 weeks Come to my office hours if you want to chat about project ideas Active data 3 Triggers 4 Constraint enforcement: When an operation violates a constraint, abort the operation or try to fix data Example: enforcing referential integrity constraints Generalize to arbitrary constraints? Data monitoring: When something happens to the data, automatically execute some action Example: When price rises above $20 per share, sell Example: When enrollment is at the limit and more students try to register, email the instructor A trigger is an event-condition-action (ECA) rule When event occurs, test condition; if condition is satisfied, execute action Example: Event: whenever there comes a new student Condition: with GPA higher than 3.0 Action: then make him/her take CPS116! Trigger example 5 Trigger options 6 CREATE TRIGGER CPS116AutoRecruit AFTER INSERT ON Student Event REFERENCING NEW ROW AS newstudent FOR EACH ROW WHEN (newstudent.gpa > 3.0) Condition INSERT INTO Enroll VALUES(newStudent.SID, CPS116 ); Action Possible events include: INSERT ON table DELETE ON table UPDATE [OF column] ON table Granularity trigger can be activated: FOR EACH ROW modified FOR EACH STATEMENT that performs modification Timing action can be executed: AFTER or BEFORE the triggering event

Transition variables OLD ROW: the modified row before the triggering event NEW ROW: the modified row after the triggering event OLD TABLE: a hypothetical read-only table containing all modified rows before the triggering event NEW TABLE: a hypothetical table containing all modified rows after the triggering event Not all of them make sense all the time, e.g. AFTER INSERT statement-level triggers Can use only NEW TABLE BEFORE DELETE row-level triggers Can use only OLD ROW etc. 7 Statement-level trigger example CREATE TRIGGER CPS116AutoRecruit AFTER INSERT ON Student REFERENCING NEW TABLE AS newstudents FOR EACH STATEMENT INSERT INTO Enroll (SELECT SID, CPS116 FROM newstudents WHERE GPA > 3.0); 8 BEFORE trigger example Never give faculty more than 50% raise in one update CREATE TRIGGER NotTooGreedy BEFORE UPDATE OF salary ON Faculty REFERENCING OLD ROW AS o, NEW ROW AS n FOR EACH ROW WHEN (n.salary > 1.5 * o.salary) SET n.salary = 1.5 * o.salary; BEFORE triggers are often used to condition data Another option is to raise an error in the trigger body to abort the transaction that caused the trigger to fire 9 Statement- vs. row-level triggers Why are both needed? Certain triggers are only possible at statement level If the average GPA of students inserted by this statement exceeds 3.0, do Simple row-level triggers are easier to implement and may be more efficient Statement-level triggers require significant amount of state to be maintained in OLD TABLE and NEW TABLE However, a row-level trigger does get fired for each row, so complex row-level triggers may be inefficient for statements that generate lots of modifications 10 Another statement-level trigger 11 System issues 12 Give faculty a raise if GPA s in one update statement are all increasing CREATE TRIGGER AutoRaise AFTER UPDATE OF GPA ON Student REFERENCING OLD TABLE AS o, NEW TABLE AS n FOR EACH STATEMENT WHEN (NOT EXISTS(SELECT * FROM o, n WHERE o.sid = n.sid AND o.gpa >= n.gpa)) UPDATE Faculty SET salary = salary + 1000; A row-level trigger would be difficult to write in this case Recursive firing of triggers Action of one trigger causes another trigger to fire Can get into an infinite loop Some DBMS restrict trigger actions Most DBMS set a maximum level of recursion (16 in DB2) Interaction with constraints (very tricky to get right!) When do we check if a triggering event violates constraints? After a BEFORE trigger (so the trigger can fix a potential violation) Before an AFTER trigger AFTER triggers also see the effects of, say, cascaded deletes caused by referential integrity constraint violations (Based on DB2; other DBMS may implement a different policy)

Views 13 Creating and dropping views 14 A view is like a virtual table Defined by a query, which describes how to compute the view contents on the fly DBMS stores the view definition query instead of view contents Can be used in queries just like a regular table Example: CPS116 roster CREATE VIEW CPS116Roster AS SELECT SID, name, age, GPA FROM Student WHERE SID IN (SELECT SID FROM Enroll WHERE CID = CPS116 ); To drop a view DROP VIEW view_name; Called base tables Using views in queries 15 Why use views? 16 Example: find the average GPA of CPS116 students SELECT AVG(GPA) FROM CPS116Roster; To process the query, replace the reference to the view by its definition SELECT AVG(GPA) FROM (SELECT SID, name, age, GPA FROM Student WHERE SID IN (SELECT SID FROM Enroll WHERE CID = CPS116 )); To hide data from users To hide complexity from users Logical data independence If applications deal with views, we can change the underlying schema without affecting applications Recall physical data independence: change the physical organization of data without affecting applications To provide a uniform interface for different implementations or sources Real database applications use tons of views Modifying views 17 A simple case 18 Does not seem to make sense since views are virtual But does make sense if that is how users see the database Goal: modify the base tables such that the modification would appear to have been accomplished on the view CREATE VIEW StudentGPA AS SELECT SID, GPA FROM Student; DELETE FROM StudentGPA WHERE SID = 123; translates to: DELETE FROM Student WHERE SID = 123;

An impossible case 19 A case with too many possibilities 20 CREATE VIEW HighGPAStudent AS SELECT SID, GPA FROM Student WHERE GPA > 3.7; INSERT INTO HighGPAStudent VALUES(987, 2.5); No matter what you do on Student, the inserted row will not be in HighGPAStudent CREATE VIEW AverageGPA(GPA) AS SELECT AVG(GPA) FROM Student; Note that you can rename columns in view definition UPDATE AverageGPA SET GPA = 2.5; Set everybody s GPA to 2.5? Adjust everybody s GPA by the same amount? Just lower Lisa s GPA? SQL92 updateable views 21 Indexes 22 More or less just single-table selection queries No join No aggregation No subqueries Arguably somewhat restrictive Still might get it wrong in some cases See the slide titled An impossible case Adding WITH CHECK OPTION to the end of the view definition will make DBMS reject such modifications An index is an auxiliary persistent data structure Search tree (e.g., B + -tree), lookup table (e.g., hash table), etc. More on indexes in the second half of this course! An index on R.A can speed up accesses of the form R.A = value R.A > value (sometimes; depending on the index type) An index on ( R.A 1,, R.A n ) can speed up R.A 1 = value 1 R.A n = value n (R.A 1, R.A n )> (value 1,, value n ) (again depends) Is an index on (R.A, R.B) equivalent to one on (R.B, R.A)? How about an index on R.A plus another index on R.B? Examples of using indexes 23 Creating and dropping indexes in SQL 24 SELECT * FROM Student WHERE name = Bart Without an index on Student.name: must scan the entire table if we store Student as a flat file of unordered rows With index: go directly to rows with name = Bart SELECT * FROM Student, Enroll WHERE Student.SID = Enroll.SID; Without any index: for each Student row, scan the entire Enroll table for matching SID Sorting could help With an index on Enroll.SID: for each Student row, directly look up Enroll rows with matching SID CREATE [UNIQUE] INDEX index_name ON table_name(column_name 1,, column_name n ); With UNIQUE, the DBMS will also enforce that {column_name 1,, column_name n } is a key of table_name DROP INDEX index_name; Typically, the DBMS will automatically create indexes for PRIMARY KEY and UNIQUE constraint declarations

Choosing indexes to create 25 26 Summary of SQL features covered so far More indexes = better performance? Indexes take space Indexes need to be maintained when data is updated Indexes have one more level of indirection Optimal index selection depends on both query and update workload and the size of tables Automatic index selection is still an area of active research Query Modification Constraints Triggers Views Indexes Next: transactions