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

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

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

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

EECS 647: Introduction to Database Systems

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

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

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

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

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

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

Integrity Constraints (Reminder)

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

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

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

The Relational Model. Week 2

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

Database Applications (15-415)

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

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

The Relational Data Model. Data Model

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

The Relational Model of Data (ii)

Relational data model

The Relational Model 2. Week 3

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

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

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

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

Database Management Systems. Chapter 3 Part 1

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

EGCI 321: Database Systems. Dr. Tanasanee Phienthrakul

The Relational Model. Chapter 3

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

Introduction to Database Systems CSE 414

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

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

Data Modelling and Databases. Exercise Session 7: Integrity Constraints

Constraints. Local and Global Constraints Triggers

Database Systems ( 資料庫系統 )

CSEN 501 CSEN501 - Databases I

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

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

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

SQL DATA DEFINITION LANGUAGE

A tuple is dangling if it doesn't join with any

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

The Relational Model. Why Study the Relational Model? Relational Database: Definitions

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

SQL DATA DEFINITION LANGUAGE

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

CSC 453 Database Technologies. Tanu Malik DePaul University

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

Lecture 2: Introduction to SQL

CS W Introduction to Databases Spring Computer Science Department Columbia University

Introduction to Data Management CSE 344

EECS 647: Introduction to Database Systems

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

SQL: Queries, Constraints, Triggers (iii)

EECS 647: Introduction to Database Systems

CS54100: Database Systems

SQL DATA DEFINITION LANGUAGE

Introduction to Data Management CSE 344

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

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

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

The Relational Model. Outline. Why Study the Relational Model? Faloutsos SCS object-relational model

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

Constraints and Triggers

Review. The Relational Model. Glossary. Review. Data Models. Why Study the Relational Model? Why use a DBMS? OS provides RAM and disk

The Relational Model. Roadmap. Relational Database: Definitions. Why Study the Relational Model? Relational database: a set of relations

The Relational Model

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

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

Relational Databases BORROWED WITH MINOR ADAPTATION FROM PROF. CHRISTOS FALOUTSOS, CMU /615

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

SQL: Data Definition Language. csc343, Introduction to Databases Diane Horton Fall 2017

SQL: A COMMERCIAL DATABASE LANGUAGE. Complex Constraints

SQL Constraints and Triggers. Week 11

Translation of ER-diagram into Relational Schema. Dr. Sunnie S. Chung CIS430/530

e e Conceptual design begins with the collection of requirements and results needed from the database (ER Diag.)

Database Systems. Course Administration

Database Management Systems Triggers

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

CompSci 516 Database Systems. Lecture 2 SQL. Instructor: Sudeepa Roy

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

Creating Tables, Defining Constraints. Rose-Hulman Institute of Technology Curt Clifton

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

The Relational Model

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

Why Study the Relational Model? The Relational Model. Relational Database: Definitions. The SQL Query Language. Relational Query Languages

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

Lecture 2 SQL. Announcements. Recap: Lecture 1. Today s topic. Semi-structured Data and XML. XML: an overview 8/30/17. Instructor: Sudeepa Roy

The DBMS accepts requests for data from the application program and instructs the operating system to transfer the appropriate data.

CS 4604: Introduc0on to Database Management Systems. B. Aditya Prakash Lecture #4: SQL---Part 2

SQL: Data Definition Language

doc. RNDr. Tomáš Skopal, Ph.D. RNDr. Michal Kopecký, Ph.D.

Data Modeling. Yanlei Diao UMass Amherst. Slides Courtesy of R. Ramakrishnan and J. Gehrke

Databases 1. Defining Tables, Constraints

Principles of Data Management

First lecture of this chapter is in slides (PPT file)

Transcription:

SQL: Part III CPS 216 Advanced Database Systems Announcements 2 Reminder: Homework #1 due in 12 days Reminder: reading assignment posted on Web Reminder: recitation session this Friday (January 31) on SQL Constraints 3 Restrictions on allowable data in a database In addition to the simple structure and type restrictions imposed by the table definitions Declared as part of the schema Enforced automatically by the DBMS Why use constraints? Protect data integrity (catch errors) Tell the DBMS about the data (so it can optimize better)

Types of SQL constraints 4 NOT NULL Key Referential integrity (foreign key) General assertion Tuple- and attribute-based CHECK s NOT NULL constraint examples 5 CREATE TABLE Student (SID INTEGER NOT NULL, name VARCHAR(30) NOT NULL, email VARCHAR(30), age INTEGER, GPA FLOAT); CREATE TABLE Course (CID CHAR(10) NOT NULL, title VARCHAR(100) NOT NULL); CREATE TABLE Enroll (SID INTEGER NOT NULL, CID CHAR(10) NOT NULL); Key declaration 6 At most one PRIMARY KEY per table Typically implies a primary index Rows are stored inside the index, typically sorted by the primary key value Any number of UNIQUE keys per table Typically implies a secondary index Pointers to rows are stored inside the index

Key declaration examples CREATE TABLE Student (SID INTEGER NOT NULL PRIMARY KEY, name VARCHAR(30) NOT NULL, email VARCHAR(30) UNIQUE, age INTEGER, GPA FLOAT); CREATE TABLE Course (CID CHAR(10) NOT NULL PRIMARY KEY, title VARCHAR(100) NOT NULL); CREATE TABLE Enroll (SID INTEGER NOT NULL, CID CHAR(10) NOT NULL, PRIMARY KEY(SID, CID)); 7 Works on Oracle but not DB2: DB2 requires UNIQUE key columns to be NOT NULL This form is required for multi-attribute keys Referential integrity example 8 Enroll.SID references Student.SID If an SID appears in Enroll, it must appear in Student Enroll.CID references Course.CID If a CID appears in Enroll, it must appear in Course That is, no dangling pointers Student SID name age GPA 142 Bart 10 2.3 123 Milhouse 10 3.1 857 Lisa 8 4.3 456 Ralph 8 2.3............ Enroll SID CID 142 CPS216 142 CPS214 123 CPS216 857 CPS216 857 CPS230 456 CPS214...... Course CID title CPS216 Advanced Database Systems CPS230 Analysis of Algorithms CPS214 Computer Networks...... Referential integrity in SQL 9 Referenced column(s) must be PRIMARY KEY Referencing column(s) form a FOREIGN KEY Example CREATE TABLE Enroll (SID INTEGER NOT NULL REFERENCES Student(SID), CID CHAR(10) NOT NULL, PRIMARY KEY(SID, CID), FOREIGN KEY CID REFERENCES Course(CID));

Enforcing referential integrity 10 Example: Enroll.SID references Student.SID Insert/update an Enroll row so it refers to a non-existent SID Reject Reject Cascade: ripple changes to all referring rows Set NULL: set all references to NULL Deferred constraint checking (e.g., only at the end of a transaction) Good for Required when General assertion 11 CREATE ASSERTION assertion_name CHECK assertion_condition; assertion_condition is checked for each modification that could potentially violate it Example: Enroll.SID references Student.SID CREATE ASSERTION EnrollStudentRefIntegrity CHECK (NOT EXISTS (SELECT * FROM Enroll WHERE SID NOT IN (SELECT SID FROM Student))); In SQL3, but not all (perhaps no) DBMS support it Tuple- and attribute-based CHECK s 12 Associated with a single table Only checked when a tuple or an attribute is inserted or updated Example: CREATE TABLE Enroll (SID INTEGER NOT NULL CHECK (SID IN (SELECT SID FROM Student)), CID...); Is it a referential integrity constraint?

13 Summary of SQL features covered so far Query SELECT-FROM-WHERE statements Set and bag operations Table expressions, subqueries Ordering Aggregation and grouping Modification INSERT/DELETE/UPDATE Constraints Next: triggers, views, indexes Active data 14 Constraint enforcement: When a transaction violates a constraint, abort the transaction or try to fix the 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 Triggers 15 A trigger is an event-condition-action 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 CPS216!

Trigger example 16 CREATE TRIGGER CPS216AutoRecruit AFTER INSERT ON Student REFERENCING NEW ROW AS newstudent FOR EACH ROW WHEN (newstudent.gpa > 3.0) INSERT INTO Enroll VALUES(newStudent.SID, CPS216 ); Trigger options 17 Possible events include: INSERT ON table DELETE ON table UPDATE [OF column] ON table Trigger can be activated: FOR EACH ROW modified FOR EACH STATEMENT that performs modification Action can be executed: AFTER or BEFORE the triggering event Transition variables 18 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 etc.

Statement-level trigger example 19 CREATE TRIGGER CPS216AutoRecruit AFTER INSERT ON Student REFERENCING NEW TABLE AS newstudents FOR EACH STATEMENT INSERT INTO Enroll (SELECT SID, CPS216 FROM newstudents WHERE GPA > 3.0); BEFORE trigger example 20 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 Statement- vs. row-level triggers 21 Why are both needed?

System issues 22 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 23 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 Creating and dropping views 24 Example: CPS216 roster CREATE VIEW CPS216Roster AS SELECT SID, name, age, GPA FROM Student WHERE SID IN (SELECT SID FROM Enroll WHERE CID = CPS216 ); To drop a view DROP VIEW view_name; Called base tables

Using views in queries 25 Example: find the average GPA of CPS216 students SELECT AVG(GPA) FROM CPS216Roster; 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 = CPS216 )); Why use views? 26 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 Real database applications use tons of views Indexes 27 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 following weeks! 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 Is an index on { R.A, R.B } equivalent to an index on R.A plus another index on R.B?

Examples of using indexes 28 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 Creating and dropping indexes in SQL 29 CREATE INDEX index_name ON table_name(column_name 1,, column_name n ); DROP INDEX index_name; Typically, the DBMS will automatically create indexes for PRIMARY KEY and UNIQUE constraint declarations Choosing indexes to create 30 More indexes = better performance? Indexes take space Indexes need to be maintained when data is updated Indexes have one more level of indirection Maybe not a problem for main memory, but can be really bad on disk 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

31 Summary of SQL features covered so far Query Modification Constraints Triggers Views Indexes Next: transactions, application programming, and then we will dive into DBMS implementation!