Databases 2012 Constraints, Triggers, and Views

Similar documents
Databases 2011 The Relational Model and SQL

Databases Normalization. Christian S. Jensen Computer Science, Aarhus University

The Relational Model and SQL

Constraints. Local and Global Constraints Triggers

Constraints and Triggers

Introduction to Data Management CSE 344

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

SQL DATA DEFINITION LANGUAGE

SQL DATA DEFINITION LANGUAGE

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

Databases 1. Defining Tables, Constraints

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

SQL DATA DEFINITION LANGUAGE

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

Introduction to Database Systems CSE 414

SQL: Data Definition Language

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

From E/R Diagrams to Relations

Introduction to Data Management CSE 344

Data Modelling and Databases. Exercise Session 7: Integrity Constraints

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

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

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

CS2300: File Structures and Introduction to Database Systems

Integrity Constraints (Reminder)

Design Techniques. 1. Avoid redundancy 2. Limit the use of weak entity sets 3. Don t use an entity set when an attribute will do

Summary Modifications. Database Construction (and Usage) Explicit attribute lists. Insertions with queries. Quiz. Default values

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

The Relational Model. Chapter 3

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

CS54100: Database Systems

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

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

The Relational Model 2. Week 3

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

The Relational Model. Week 2

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

SQL: Data De ni on. B0B36DBS, BD6B36DBS: Database Systems. h p:// Lecture 3

EGCI 321: Database Systems. Dr. Tanasanee Phienthrakul

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

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

Concepts of Database Management Seventh Edition. Chapter 4 The Relational Model 3: Advanced Topics

CSE 344 AUGUST 1 ST ENTITIES

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

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

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

Introduction to Data Management CSE 344

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

IBM DB2 UDB V7.1 Family Fundamentals.

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

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

Relational data model

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

SQL DATA DEFINITION: KEY CONSTRAINTS. CS121: Relational Databases Fall 2017 Lecture 7

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

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

Create a simple database with MySQL

The Relational Model of Data (ii)

Advanced Constraints SQL. by Joe Celko copyright 2007

For the Dorm Energy Monitoring DB design, some constraints are given and some are absent. You are asked to fill in some of these absent constraints.

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

CSE 344 MAY 14 TH ENTITIES

MySQL. A practical introduction to database design

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

Where are we? Week -4: Data definition (Creation of the schema) Week -3: Data definition (Triggers) Week -1: Transactions and concurrency in ORACLE.

The Relational Model

Part I: Structured Data

THE UNIVERSITY OF AUCKLAND

Indexes (continued) Customer table with record numbers. Source: Concepts of Database Management

Full file at

Principles of Data Management

Database Technology. Topic 6: Triggers and Stored Procedures

Debapriyo Majumdar DBMS Fall 2016 Indian Statistical Institute Kolkata

SQL Server. Lecture3 Cascading referential integrity constraint

Consistency The DBMS must ensure the database will always be in a consistent state. Whenever data is modified, the database will change from one

SQL Constraints and Triggers

PASS4TEST. IT Certification Guaranteed, The Easy Way! We offer free update service for one year

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

Interview Questions on DBMS and SQL [Compiled by M V Kamal, Associate Professor, CSE Dept]

CS W Introduction to Databases Spring Computer Science Department Columbia University

The Relational Data Model. Data Model

Database Management Systems. Chapter 3 Part 2

COSC 304 Introduction to Database Systems SQL DDL. Dr. Ramon Lawrence University of British Columbia Okanagan

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

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

Intermediate SQL ( )

Introduction to Databases

Databases 2012 Embedded SQL

Handout 6 CS-605 Spring 18 Page 1 of 7. Handout 6. Physical Database Modeling

DATABASES SQL INFOTEK SOLUTIONS TEAM

1- a> [5pts] Create the new table by writing and executing a full SQL DDL statement based on the following schema:

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

Ebook : Overview of application development. All code from the application series books listed at:

COMP283-Lecture 6 Applied Database Management

CS143: Relational Model

Introduction to MySQL /MariaDB and SQL Basics. Read Chapter 3!

Database Applications (15-415)

STORED PROCEDURE AND TRIGGERS

Chapter 9: Working With Data

Database Management Systems. Chapter 3 Part 1

Transcription:

Databases 2012 Christian S. Jensen Computer Science, Aarhus University

Constraints Enforced relationships among data single-attribute keys multi-attribute keys foreign keys attribute constraints row constraints assertions Different scopes of constraints Different policies for enforcement 2

Single-Attribute Key NOT NULL the value cannot be NULL DEFAULT value a default value is specified UNIQUE the value is unique in the table unless it is NULL PRIMARY KEY the value is unique in the table the value is never NULL 3

Example CREATE TABLE People ( name VARCHAR(40) NOT NULL, office VARCHAR(15), userid VARCHAR(15) PRIMARY KEY, `group` CHAR(3) ); 4

Multi-Attribute Key PRIMARY KEY ( a 1, a 2,..., a n ) A top-level element of the CREATE statement CREATE TABLE Exams ( studentid CHAR(8), date DATE, time TIME, vip VARCHAR(15), room VARCHAR(40), PRIMARY KEY (studentid, date) ); 5

Enforcing Key Constraints Checked during insert or update If it is violated then a runtime error occurs INSERT INTO Exams VALUES('2008001', '2011-10-15', '15:30:00', csj','turing-230'); INSERT INTO Exams VALUES('2008001', '2011-10-15', '12:45:00', 'amoeller', 'Ada-017'); 6

Foreign Key Specifies that an attribute must reference an attribute in another table The referenced attribute must be a primary key Also possible for multi-attribute keys Similar to E/R constraints: Course Teaches Professor 7

Example CREATE TABLE Rooms ( room VARCHAR(15) PRIMARY KEY, capacity INT ); CREATE TABLE People ( name VARCHAR(40) NOT NULL, office VARCHAR(15) REFERENCES Rooms(room), userid VARCHAR(15) PRIMARY KEY, `group` CHAR(3) ); 8

Enforcing Foreign Key Constraints Source or target table may change Spurious value due to insert or update in source reject the insert or update Dangling value due to delete or update in target default: reject the delete or update cascade: make the same changes in the source set NULL: change source values to NULL 9

room People (source) Example Tables Rooms (target) Turing-216 4 Ada-333 26 Hopper-017 4 capacity userid name group office csj Christian S. Jensen vip Turing-216 doina Doina Bucur phd NULL bnielsen Kai Birger Nielsen tap Hopper-017 10

Example Modifications DELETE FROM Rooms WHERE room= 'Hopper-017'; UPDATE Rooms SET room = 'Turing-HQ' WHERE room = 'Turing-216'; 11

The Cascade Policy People userid name group office csj Christian S. Jensen vip Turing-HQ doina Doina Bucur phd NULL 12

The Set NULL Policy People userid name group office csj Christian S. Jensen vip NULL doina Doina Bucur phd NULL bnielsen Kai Birger Nielsen tap NULL 13

Specifying Policies CREATE TABLE People ( name VARCHAR(40) NOT NULL, office VARCHAR(15) REFERENCES Rooms(room) ON DELETE SET NULL ON UPDATE CASCADE, userid VARCHAR(15) PRIMARY KEY, `group` CHAR(3) ); 14

Attribute Constraints CHECK ( condition ) after an attribute Allows any SQL Boolean including subqueries CREATE TABLE People ( name VARCHAR(40) NOT NULL, office VARCHAR(15), userid VARCHAR(15) PRIMARY KEY, `group` CHAR(3) CHECK (`group`= 'vip' OR `group`= 'phd' OR `group`= 'tap') ); 15

Enforcing Attribute Constraints Conditions are checked during insert or update of the attribute, but not for other modifications Thus, foreign keys cannot be enforced: CREATE TABLE People ( ); name office userid `group` VARCHAR(40) NOT NULL, VARCHAR(15) CHECK (office IN (SELECT room FROM Rooms)), VARCHAR(15) PRIMARY KEY, CHAR(3) 16

Row Constraints CHECK ( condition ) at top-level Conditions are checked during insert or update of any attribute CREATE TABLE Meetings ( ); meetid date slot owner what INT, DATE, INT, VARCHAR(15), VARCHAR(40), CHECK (slot > 16 OR what NOT LIKE '%beer%') 17

Assertions Global constraints on the entire database CREATE ASSERTION StayOutOfMyOffice CHECK ( (SELECT COUNT(*) FROM People WHERE office= 'Turing-216') <= 1 ); Not in MySQL, DB2 18

Enforcing Assertions Checked after every database modification But a clever system can analyze which changes can possibly affect the assertion For StayOutOfMyOffice, we can ignore modifications of tables other than People deletions from People insertions into People where office Turing-216 updates of People where office is unchanged 19

Triggers Constraints have fixed reactions to violations Triggers enable general reactions Three components event: AFTER, BEFORE for each of INSERT, DELETE, UPDATE condition: any SQL Boolean expression action: any sequence of SQL modifications 20

Triggers as A Sweet Spot Attribute and row checks are efficient, but not really expressive Assertions are expressive, but not really efficient Triggers have the potential to be both and they can do much more just checks The database becomes active 21

Example CREATE TRIGGER ZombieOffice AFTER INSERT ON People REFERENCING NEW ROW AS NewGuy FOR EACH ROW WHEN (NewGuy.office NOT IN (SELECT room FROM Rooms)) INSERT INTO Rooms(room,capacity) VALUES(NewGuy.office,4); 22

AFTER vs. BEFORE CREATE TRIGGER GetOutOfMyOffice BEFORE INSERT ON People REFERENCING NEW ROW AS NewGuy FOR EACH ROW WHEN (NewGuy.office = 'Turing-216') SET NewGuy.office = 'Turing-224'; 23

INSERT, DELETE, Or UPDATE CREATE TRIGGER GetOutOfMyOffice2 BEFORE UPDATE ON People REFERENCING NEW ROW AS NewGuy FOR EACH ROW WHEN (NewGuy.office = 'Turing-216') SET NewGuy.office = 'Turing-224'; 24

Row-Level Or Statement-Level FOR EACH ROW performs the action once for each row FOR EACH STATEMENT performs the action once CREATE TRIGGER LogInsert AFTER INSERT ON People FOR EACH STATEMENT INSERT INTO LogFile VALUES('People', CURRENT_TIME); 25

Referencing Old And New An INSERT implies a new row (FOR EACH ROW) a new table (FOR EACH STATEMENT) A DELETE implies an old row (FOR EACH ROW) an old table (FOR EACH STATEMENT) An UPDATE implies both new and old versions These are refered to as NEW,OLD ROW, TABLE 26

Example CREATE TRIGGER PromotionOfficeDefault AFTER UPDATE ON People REFERENCING OLD ROW AS OldGuy FOR EACH ROW NEW ROW AS NewGuy WHEN (OldGuy.group = 'phd' AND NewGuy.group = 'vip' AND NewGuy.office IS NULL) UPDATE People SET office = 'Turing-224' WHERE userid = NewGuy.userid; 27

Views A view is a virtual table/a named query defined as a function of base tables or other views CREATE VIEW Vips AS SELECT * FROM People WHERE `group` = 'vip'; SELECT * FROM Vips; 28

A Joined View CREATE VIEW BusyDays AS SELECT name, date FROM People, Meetings WHERE People.userid = Meetings.owner; SELECT * FROM BusyDays, Vips WHERE BusyDays.name = Vips.name; 29

Meaning of Views View definitions are pasted in place of uses: SELECT * FROM BusyDays, Vips WHERE BusyDays.name = Vips.name; SELECT * FROM (SELECT name, date FROM People, Meetings WHERE People.userid = Meetings.owner) BusyDays, (SELECT * FROM People WHERE `group` = 'vip') Vips WHERE BusyDays.name = Vips.name; 30

Materialized Views Views may alternatively be stored as tables CREATE MATERIALIZED VIEW VipsM AS SELECT * FROM People WHERE group = 'vip'; This requires recomputation whenever the view may have changed 31

Efficiency Trade-Off A materialized view is faster for queries slower for modifications A typical compromise: recompute the view periodically This only works if correctness is not critical mailing spam to customers computing pie charts from sales statistics 32

Modifying Views Generally, it makes no sense to update a view CREATE VIEW AvgCap AS SELECT AVG(capacity) AS average FROM Rooms; UPDATE AvgCap SET average=117; The function is not reversible... 33

Modifiable Views (1/2) Particularly simple views may be modifed only a single table in FROM only SELECT (enough) simple attributes no subqueries in WHERE INSERT INTO Vips VALUES ('Glynn Winskel', 'Turing-222', 'gwinskel', 'vip'); 34

Modifiable Views (2/2) Defaults or NULL appear for missing attributes 35

INSTEAD-OF Triggers Triggers may be used to catch view modifications The intended action is then performed on the underlying base tables This allows human insight to be used 36

Example CREATE VIEW Vips AS SELECT userid, name, office FROM People WHERE `group` = 'vip'; CREATE TRIGGER VipsInsert INSTEAD OF INSERT ON Vips REFERENCING NEW ROW AS NewVip FOR EACH ROW INSERT INTO People VALUES(NewVip.userid, NewVip.name, 'vip', NewVip.office); INSERT INTO Vips VALUES('gwinskel', 'Glynn Winskel', NULL); 37

Another Example CREATE VIEW BusyDays AS SELECT name, date FROM People, Meetings WHERE People.userid = Meetings.owner; CREATE TRIGGER BusyDaysDelete INSTEAD OF DELETE ON BusyDays REFERENCING OLD ROW AS OldDay FOR EACH ROW DELETE FROM Meetings WHERE date = OldDay.date AND owner IN (SELECT userid FROM People WHERE name = OldDay.name); 38

MySQL Code DELIMITER $$ CREATE TRIGGER ZombieOffice AFTER INSERT ON People FOR EACH ROW BEGIN IF (NEW.office NOT IN (SELECT room FROM Rooms)) THEN INSERT INTO Rooms(room,capacity) VALUES(NEW.office,4); END IF; END$$ DELIMITER ; 39

MySQL Code DELIMITER $$ CREATE TRIGGER GetOutOfMyOffice BEFORE INSERT ON People FOR EACH ROW BEGIN IF (NEW.office = 'Turing-216') THEN SET NEW.office = 'Turing-224'; END IF; END$$ DELIMITER ; 40

MySQL Code DELIMITER $$ CREATE TRIGGER GetOutOfMyOffice2 BEFORE UPDATE ON People FOR EACH ROW BEGIN IF (NEW.office = 'Turing-216') THEN SET NEW.office = 'Turing-224'; END IF; END$$ DELIMITER ; 41

MySQL Code DELIMITER $$ CREATE TRIGGER PromotionOfficeDefault AFTER UPDATE ON People FOR EACH ROW BEGIN IF (OLD.group = 'phd' AND NEW.group = 'vip' AND NEW.office IS NULL) THEN UPDATE People SET office = 'Turing-224 WHERE userid = NEW.userid; END IF; END$$ DELIMITER ; 42

MySQL Code MySQL 5.1 does not support triggers with FOR EACH STATEMENT Materialized views are not supported in MySQL. INSTEAD OF triggers are not supported in MySQL. 43