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

Similar documents
SQL: Queries, Constraints, Triggers (iii)

The Relational Model of Data (ii)

Relational Model, Key Constraints

One Size Fits All: An Idea Whose Time Has Come and Gone

SQL. Chapter 5 FROM WHERE

The Relational Model (ii)

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

High-Level Database Models (ii)

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

SQL: Queries, Constraints, Triggers

The Relational Data Model. Data Model

Lecture 3 More SQL. Instructor: Sudeepa Roy. CompSci 516: Database Systems

SQL: Queries, Programming, Triggers

SQL: Queries, Programming, Triggers. Basic SQL Query. Conceptual Evaluation Strategy. Example of Conceptual Evaluation. A Note on Range Variables

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

The SQL Query Language. Creating Relations in SQL. Adding and Deleting Tuples. Destroying and Alterating Relations. Conceptual Evaluation Strategy

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

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

The Relational Model. Chapter 3

Database Management Systems. Chapter 3 Part 1

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

The Relational Model 2. Week 3

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

Integrity Constraints (Reminder)

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

Relational data model

High Level Database Models

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

SQL Constraints and Triggers. Week 11

SQL: Queries, Programming, Triggers

CIS 330: Applied Database Systems

Database Applications (15-415)

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

The Relational Model

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

Data Modelling and Databases. Exercise Session 7: Integrity Constraints

EGCI 321: Database Systems. Dr. Tanasanee Phienthrakul

The Database Language SQL (i)

Outer Join, More on SQL Constraints

Overview of DB & IR. ICS 624 Spring Asst. Prof. Lipyeow Lim Information & Computer Science Department University of Hawaii at Manoa

CIS 330: Applied Database Systems. ER to Relational Relational Algebra

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

The Relational Model

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

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. Week 2

SQL: The Query Language Part 1. Relational Query Languages

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

Intermediate SQL ( )

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

Keys, SQL, and Views CMPSCI 645

Midterm Exam #2 (Version A) CS 122A Winter 2017

Data Definition Language (DDL), Views and Indexes Instructor: Shel Finkelstein

Lecture 3 SQL - 2. Today s topic. Recap: Lecture 2. Basic SQL Query. Conceptual Evaluation Strategy 9/3/17. Instructor: Sudeepa Roy

Query Evaluation (i)

CSEN 501 CSEN501 - Databases I

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

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

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

Relational Algebra. Spring 2012 Instructor: Hassan Khosravi

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

Introduction to Data Management. Lecture #5 (E-R Relational, Cont.)

AC61/AT61 DATABASE MANAGEMENT SYSTEMS DEC 2013

Information Systems Engineering. SQL Structured Query Language DDL Data Definition (sub)language

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

Review: Where have we been?

SQL queries II. Set operations and joins

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

Overview of Query Processing

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

Introduction to Database Systems CSE 414

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

Database Systems ( 資料庫系統 )

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

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

EECS 647: Introduction to Database Systems

CS W Introduction to Databases Spring Computer Science Department Columbia University

Rewrite INTERSECT using IN

CITS3240 Databases Mid-semester 2008

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

D B M G. SQL language: basics. Managing tables. Creating a table Modifying table structure Deleting a table The data dictionary Data integrity

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

Transactions Processing (i)

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

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

Set Operations, Union

The Relational Model

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

Enterprise Database Systems

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

Introduction to Database Systems. Announcements CSE 444. Review: Closure, Key, Superkey. Decomposition: Schema Design using FD

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

Announcements If you are enrolled to the class, but have not received the from Piazza, please send me an . Recap: Lecture 1.

HW2 out! Administrative Notes

Today s topics. Null Values. Nulls and Views in SQL. Standard Boolean 2-valued logic 9/5/17. 2-valued logic does not work for nulls

Extension to SQL: View, Triggers, Transaction. SS Chung

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

Data Warehousing 3. ICS 421 Spring Asst. Prof. Lipyeow Lim Information & Computer Science Department University of Hawaii at Manoa

Introduction to Data Management CSE 344

Database Modifications and Transactions

Transcription:

ICS 321 Spring 2011 Constraints, Triggers, Views & Indexes Asst. Prof. Lipyeow Lim Information & Computer Science Department University of Hawaii at Manoa 04/04/2011 Lipyeow Lim -- University of Hawaii at Manoa 1

PK and FK Constraints CREATE TABLE Studio ( name CHAR(30) NOT NULL PRIMARY KEY, address VARCHAR(255), presc# INT REFERENCES MovieExec(cert#) ) CREATE TABLE Studio ( Cert# must be name CHAR(30) NOT NULL, address VARCHAR(255), declared with presc# INT, PRIMARY KEY or PRIMARY KEY(name), UNIQUE constraint FOREIGN KEY(presC#) REFERENCES MovieExec(cert#) ) 04/04/2011 Lipyeow Lim -- University of Hawaii at Manoa 2

Maintaining Referential Integrity CREATE TABLE Studio ( name CHAR(30) NOT NULL PRIMARY KEY, address VARCHAR(255), presc# INT REFERENCES MovieExec(cert#) ) INSERT INTO studio VALUES (...) UPDATE studio SET presc#=?... DELETE FROM MovieExec WHERE... UPDATE MovieExec SET cert#=?... If new presc# value does not exist in MovieExec, reject! If deleted cert# values are used in studio, reject! If old cert# values are used in studio, reject! 04/04/2011 Lipyeow Lim -- University of Hawaii at Manoa 3

Other Options for Referential Integrity CREATE TABLE Studio ( name CHAR(30) NOT NULL PRIMARY KEY, address VARCHAR(255), presc# INT REFERENCES MovieExec(cert#) ON DELETE SET NULL ON UPDATE CASCADE ) CASCADE : changes to referenced attributes are mimicked at FK. SET NULL : changes to referenced attributes makes affected FK null DEFERABLE : checking can wait till end of transaction INITIALLY DEFERRED : defer checking INITIALLY IMMEDIATE : check immediately 04/04/2011 Lipyeow Lim -- University of Hawaii at Manoa 4

Check Constraints Attribute, tuple-based, multi-table Syntax: CHECK conditional-expression CREATE TABLE Studio ( name CHAR(30) NOT NULL PRIMARY KEY, address VARCHAR(255), presc# INT REFERENCES MovieExec(cert#) CHECK ( presc# >=100000 ) ) CREATE TABLE MovieStar ( name CHAR(30) NOT NULL PRIMARY KEY, address VARCHAR(255), gender CHAR(1), birthdate DATE, CHECK ( gender = F OR name NOT LIKE Ms.% ) ) 04/04/2011 Lipyeow Lim -- University of Hawaii at Manoa 5

Naming Constraints CREATE TABLE Studio ( name CHAR(30) CONSTRAINT nameiskey PRIMARY KEY, address VARCHAR(255), presc# INT REFERENCES MovieExec(cert#) CONSTRAINT sixdigit CHECK ( presc# >=100000 ) ) ALTER TABLE Studio DROP CONSTRAINT nameiskey; ALTER TABLE Studio ADD CONSTRAINT nameiskey PRIMARY KEY(name) ; Constraints can be named, so that you can refer to them in alter table statements 04/04/2011 Lipyeow Lim -- University of Hawaii at Manoa 6

Constraints over Multiple Tables Example: number of boats + number of sailors < 100 CREATE TABLE Sailors ( sid INTEGER, sname CHAR(10), rating INTEGER, age REAL, PRIMARY KEY (sid), CHECK ( (SELECT COUNT (S.sid) FROM Sailors S) + (SELECT COUNT (B.bid) FROM Boats B) < 100 ) When is the constraint enforced? What happens if the sailors table is empty? Think of a case when the constraint is violated but the system never catches it. 04/04/2011 Lipyeow Lim -- University of Hawaii at Manoa 7

CREATE ASSERTION Allows constraints that are not associated with any table. Evaluated whenever tables in the condition are updated CREATE ASSERTION smallclub CHECK ( (SELECT COUNT (S.sid) FROM Sailors S) + (SELECT COUNT (B.bid) FROM Boats B) < 100 ) 04/04/2011 Lipyeow Lim -- University of Hawaii at Manoa 8

Triggers Trigger: procedure that starts automatically if specified changes occur to the DBMS Three parts: Event (activates the trigger) Condition (tests whether the triggers should run) Action (what happens if the trigger runs) 04/04/2011 Lipyeow Lim -- University of Hawaii at Manoa 9

Example of a Trigger CREATE TRIGGER youngsailorupdate AFTER INSERT ON SAILORS REFERENCING NEW TABLE NewSailors FOR EACH STATEMENT INSERT INTO YoungSailors(sid, name, age, rating) SELECT sid, name, age, rating FROM NewSailors N WHERE N.age <= 18 Why is NewSailors needed? What is the difference between a constraint and a trigger? 04/04/2011 Lipyeow Lim -- University of Hawaii at Manoa 10

Another Example of a Trigger Create a trigger that will cause an error when an update occurs that would result in a salary increase greater than ten percent of the current salary. CREATE TRIGGER RAISE_LIMIT AFTER UPDATE OF SALARY ON EMPLOYEE REFERENCING NEW AS N OLD AS O FOR EACH ROW WHEN (N.SALARY > 1.1 * O.SALARY) SIGNAL SQLSTATE '75000' SET MESSAGE_TEXT='Salary increase>10%' 04/04/2011 Lipyeow Lim -- University of Hawaii at Manoa 11

Views CREATE VIEW YoungActiveStudents (name, grade) AS SELECT S.name, E.grade FROM Students S, Enrolled E WHERE S.sid = E.sid and S.age<21 A view is just a relation, but we store a definition, rather than a set of tuples. Views can be dropped using the DROP VIEW command. What if table that the view is dependent on is dropped? DROP TABLE command has options to let the user specify this. 04/04/2011 Lipyeow Lim -- University of Hawaii at Manoa 12

Querying Views CREATE VIEW YoungActiveStudents (name, grade) AS SELECT S.name, E.grade FROM Students S, Enrolled E WHERE S.sid = E.sid and S.age<21 SELECT name FROM YoungActiveStudents WHERE grade = A Query views as with any table Conceptually, you can think of rewriting using a subquery SELECT name FROM (SELECT S.name, E.grade FROM Students S, Enrolled E WHERE S.sid = E.sid and S.age<21) WHERE grade = A 04/04/2011 Lipyeow Lim -- University of Hawaii at Manoa 13

Updateable Views In general views are not updateable. Why? A view on R is updateable when WHERE : must not involve R in a subquery FROM : only one occurrence of R and no joins. SELECT : include enough attributes to fill out other attributes in R CREATE VIEW ParamountMovies AS SELECT title, year FROM movies WHERE studioname= Paramount SELECT * FROM ParamountMovies INSERT INTO ParamountMovies VALUES ( Star Trek, 1979) INSERT INTO Movies ( title, year ) VALUES ( Star Trek, 1979) 04/04/2011 Lipyeow Lim -- University of Hawaii at Manoa 14

Indexes in SQL SELECT * FROM Movies WHERE studioname= Disney AND year=1990 Title Year Length Genre studio Name... 1990 produc erc# 10,000 rows 200 movies are made in 1990 An index on attribute A is a data structure that makes it efficient to find those tuples that have a fixed value for attribute A 04/04/2011 Lipyeow Lim -- University of Hawaii at Manoa 15

Creating Indexes CREATE INDEX myidx ON mytable(col1, col3) CREATE UNIQUE INDEX myuniqidx ON mytable(col2, col5) CREATE INDEX myidx ON mytable(col1, col3) CLUSTER Clustered Index : an index on an attribute that the tuples are sorted in. If a primary key is specified in the CREATE TABLE statement, an (unclustered) index is automatically created for the PK. To create a clustered PK index: Create table without PK constraint Create index on PK with cluster option Alter table to add PK constraint To get rid of unused indexes: DROP INDEX myidx; 04/04/2011 Lipyeow Lim -- University of Hawaii at Manoa 16

Materialized Views CREATE VIEW ParamountMovies AS SELECT title, year FROM movies WHERE studioname= Paramount CREATE TABLE ParamountMovies AS (SELECT title, year FROM movies WHERE studioname= Paramount ) Views can be materialized for efficiency Updating the materialized view (materialized query table in DB2) : incremental or batch Queries on base relation may be able to exploit materialized views! SELECT title FROM movies WHERE studioname= Paramount AND year=1990) 04/04/2011 Lipyeow Lim -- University of Hawaii at Manoa 17