CS54100: Database Systems

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

Constraints. Local and Global Constraints Triggers

Databases 1. Defining Tables, Constraints

Constraints and Triggers

Outerjoins, Constraints, Triggers

SQL DATA DEFINITION LANGUAGE

From E/R Diagrams to Relations

SQL: Data Definition Language

SQL DATA DEFINITION LANGUAGE

SQL DATA DEFINITION LANGUAGE

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

Introduction to SQL. Multirelation Queries Subqueries. Slides are reused by the approval of Jeffrey Ullman s

Interpretation is not exactly ëmissing value." There could be many reasons why no value is

Databases-1 Lecture-01. Introduction, Relational Algebra

SQL Continued! Outerjoins, Aggregations, Grouping, Data Modification

Chapter 2 The relational Model of data. Relational model introduction

Chapter 6 The database Language SQL as a tutorial

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

EXTENDED RELATIONAL ALGEBRA OUTERJOINS, GROUPING/AGGREGATION INSERT/DELETE/UPDATE

Introduction to SQL. Select-From-Where Statements Multirelation Queries Subqueries

More SQL. Extended Relational Algebra Outerjoins, Grouping/Aggregation Insert/Delete/Update

Introduction to SQL SELECT-FROM-WHERE STATEMENTS SUBQUERIES DATABASE SYSTEMS AND CONCEPTS, CSCI 3030U, UOIT, COURSE INSTRUCTOR: JAREK SZLICHTA

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

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

types, but key declarations and constraints Similar CREATE X commands for other schema ëdrop X name" deletes the created element of beer VARCHARè20è,

SQL: Concepts. Todd Bacastow IST 210: Organization of Data 2/17/ IST 210

Introduction to SQL. Select-From-Where Statements Multirelation Queries Subqueries. Slides are reused by the approval of Jeffrey Ullman s

CS W Introduction to Databases Spring Computer Science Department Columbia University

CS145 Introduction. About CS145 Relational Model, Schemas, SQL Semistructured Model, XML

Views, Indexes, Authorization. Views. Views 8/6/18. Virtual and Materialized Views Speeding Accesses to Data Grant/Revoke Priviledges

Chapter 6 The database Language SQL as a tutorial

CSCI3030U Database Models

CS 317/387. A Relation is a Table. Schemas. Towards SQL - Relational Algebra. name manf Winterbrew Pete s Bud Lite Anheuser-Busch Beers

Databases 1. SQL/PSM and Oracle PL/SQL

CS54100: Database Systems

Outline. CS 235: Introduction to Databases. DB Application Programming. Interface Solutions. Basic PSM Form. Persistent Stored Modules

Database Design and Programming

Subqueries. Must use a tuple-variable to name tuples of the result

CS2300: File Structures and Introduction to Database Systems

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

CSCD43: Database Systems Technology. Lecture 4

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

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

CSC 343 Winter SQL: Aggregation, Joins, and Triggers MICHAEL LIUT

Transactions, Views, Indexes. Controlling Concurrent Behavior Virtual and Materialized Views Speeding Accesses to Data

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

Real SQL Programming Persistent Stored Modules (PSM)

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

Why SQL? SQL is a very-high-level language. Database management system figures out best way to execute query

Introduction to Database Systems CSE 414

SQL: Data Manipulation Language

Chapter 2 The relational Model of data. Relational algebra

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

Beersèname, manfè. Likesèdrinker, beerè. Sellsèbar, beer, priceè. Frequentsèdrinker, barè

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

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

SQL. The Basics Advanced Manipulation Constraints Authorization 1. 1

Schedule. Today: Feb. 21 (TH) Feb. 28 (TH) Feb. 26 (T) Mar. 5 (T) Read Sections , Project Part 6 due.

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

Chapter 10 Advanced topics in relational databases

Relational Algebra and SQL. Basic Operations Algebra of Bags

CSC 261/461 Database Systems Lecture 6. Fall 2017

DATABASE TECHNOLOGY - 1MB025 (also 1DL029, 1DL300+1DL400)

Likesèdrinker, beerè. Sellsèbar, beer, priceè. Frequentsèdrinker, barè

5 Integrity Constraints and Triggers

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

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

Database Management

SQL: A COMMERCIAL DATABASE LANGUAGE. Data Change Statements,

Domain Constraints Referential Integrity Assertions Triggers. Authorization Authorization in SQL

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

Contains slides made by Naci Akkøk, Pål Halvorsen, Arthur M. Keller, Vera Goebel

CSCI 127 Introduction to Database Systems

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

SQL Functionality SQL. Creating Relation Schemas. Creating Relation Schemas

On-Line Application Processing

Relational Algebra. Algebra of Bags

Introduction to Data Management CSE 344

Chapter 4. Basic SQL. Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

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

Module 9: Managing Schema Objects

The Relational Model 2. Week 3

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

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

EGCI 321: Database Systems. Dr. Tanasanee Phienthrakul

Relational data model

Debapriyo Majumdar DBMS Fall 2016 Indian Statistical Institute Kolkata

Chapter 4: Intermediate SQL

SQL Constraints and Triggers

Chapter 9 SQL in a server environment

Database Management Systems. Chapter 3 Part 1

Introduction to Data Management CSE 344

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

1 Relational Data Model

Data Modelling and Databases. Exercise Session 7: Integrity Constraints

Recap and Schedule. Till Now: Today: Ø Query Languages: Relational Algebra; SQL. Ø Datalog A logical query language. Ø SQL Recursion.

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

Design Theory for Relational Databases

Debapriyo Majumdar DBMS Fall 2016 Indian Statistical Institute Kolkata

Lecture 08. Spring 2018 Borough of Manhattan Community College

Transcription:

CS54100: Database Systems SQL DDL 27 January 2012 Prof. Chris Clifton Defining a Database Schema CREATE TABLE name (list of elements). Principal elements are attributes and their types, but key declarations and constraints also appear. Similar CREATE X commands for other schema elements X: views, indexes, assertions, triggers. DROP X name deletes the created element of kind X with that name. beer VARCHAR(20), price REAL DROP TABLE Sells; Spring 2012 Chris Clifton - CS54100 2 2012 Chris Clifton 1

Constraints Commercial relational systems allow much more fine-tuning of constraints than do the modeling languages we learned earlier. In essence: SQL programming is used to describe constraints. Outline 1. Primary key declarations. 2. Foreign-keys = referential integrity constraints. 3. Attribute- and tuple-based checks = constraints within relations. 4. SQL Assertions = global constraints. Not found in Oracle. 5. Oracle Triggers. A substitute for assertions. Spring 2012 Chris Clifton - CS54100 3 Declaring Keys Use PRIMARY KEY or UNIQUE. But only one primary key, many UNIQUEs allowed. SQL permits implementations to create an index (data structure to speed access given a key value) in response to PRIMARY KEY only. But PostgreSQL and Oracle create indexes for both. SQL does not allow nulls in primary key, but allows them in unique columns (which may have two or more nulls, but not repeated nonnull values). Spring 2012 Chris Clifton - CS54100 4 2012 Chris Clifton 2

Two places to declare: Declaring Keys 1. After an attribute s type, if the attribute is a key by itself. 2. As a separate element. Essential if key is >1 attribute. Spring 2012 Chris Clifton - CS54100 5 beer VARCHAR(20), price REAL, PRIMARY KEY(bar,beer) Spring 2012 Chris Clifton - CS54100 6 2012 Chris Clifton 3

beer VARCHAR(20), price REAL, UNIQUE(bar,beer) is different than: bar CHAR(20) UNIQUE, beer VARCHAR(20) UNIQUE, price REAL Spring 2012 Chris Clifton - CS54100 7 Other Properties You Can Give to Attributes 1. NOT NULL = every tuple must have a real value for this attribute. 2. DEFAULT value = a value to use whenever no other value of this attribute is known. CREATE TABLE Drinkers ( name CHAR(30) PRIMARY KEY, addr CHAR(50) DEFAULT '123 Sesame St', phone CHAR(16) Spring 2012 Chris Clifton - CS54100 8 2012 Chris Clifton 4

INSERT INTO Drinkers(name) VALUES('Sally') results in the following tuple: name addr phone Sally 123 Sesame St. NULL Primary key is by default not NULL. This insert is legal. OK to list a subset of the attributes and values for only this subset. But if we had declared phone CHAR(16) NOT NULL then the insertion could not be made. Spring 2012 Chris Clifton - CS54100 9 Interesting Defaults DEFAULT CURRENT_TIMESTAMP SEQUENCE CREATE SEQUENCE customer_seq; CREATE TABLE Customer ( customerid INTEGER DEFAULT nextval('customer_seq'), name VARCHAR(30) Spring 2012 Chris Clifton - CS54100 10 2012 Chris Clifton 5

Foreign Keys In relation R a clause that attribute A references S(B) says that whatever values appear in the A column of R must also appear in the B column of relation S. B must be declared the primary key for S. CREATE TABLE Beers ( name CHAR(20) PRIMARY KEY, manf CHAR(20) beer CHAR(20) REFERENCES Beers(name), price REAL Spring 2012 Chris Clifton - CS54100 11 Alternative: add another element declaring the foreign key, as: beer CHAR(20), price REAL, FOREIGN KEY beer REFERENCES Beers(name) Extra element essential if the foreign key is more than one attribute. Spring 2012 Chris Clifton - CS54100 12 2012 Chris Clifton 6

What Happens When a Foreign Key Constraint is Violated? Two ways: 1. Insert or update a Sells tuple so it refers to a nonexistent beer. Always rejected. 2. Delete or update a Beers tuple that has a beer value some Sells tuples refer to. a) Default: reject. b) Cascade: Ripple changes to referring Sells tuple. Delete Bud. Cascade deletes all Sells tuples that mention Bud. Update Bud to Budweiser. Change all Sells tuples with Bud in beer column to be Budweiser. Spring 2012 Chris Clifton - CS54100 13 c) Set Null: Change referring tuples to have NULL in referring components. Delete Bud. Set-null makes all Sells tuples with Bud in the beer component have NULL there. Update Bud to Budweiser. Same change. Spring 2012 Chris Clifton - CS54100 14 2012 Chris Clifton 7

Selecting a Policy Add ON [DELETE, UPDATE] [CASCADE, SET NULL] to declaration of foreign key. beer CHAR(20), price REAL, FOREIGN KEY beer REFERENCES Beers(name) ON DELETE SET NULL ON UPDATE CASCADE Correct policy is a design decision. E.g., what does it mean if a beer goes away? What if a beer changes its name? Spring 2012 Chris Clifton - CS54100 15 Attribute-Based Checks Follow an attribute by a condition that must hold for that attribute in each tuple of its relation. Form: CHECK (condition). Condition may involve the checked attribute. Other attributes and relations may be involved, but only in subqueries. Oracle: No subqueries allowed in condition. Condition is checked only when the associated attribute changes (i.e., an insert or update occurs). Spring 2012 Chris Clifton - CS54100 16 2012 Chris Clifton 8

beer CHAR(20) CHECK( beer IN (SELECT name FROM Beers) ), price REAL CHECK( price <= 5.00 ) Check on beer is like a foreign-key constraint, except: The check occurs only when we add a tuple or change the beer in an existing tuple, not when we delete a tuple from Beers. Spring 2012 Chris Clifton - CS54100 17 Tuple-Based Checks Separate element of table declaration. Form: like attribute-based check. But condition can refer to any attribute of the relation. Or to other relations/attributes in subqueries. Again: Oracle forbids the use of subqueries. Checked whenever a tuple is inserted or updated. Spring 2012 Chris Clifton - CS54100 19 2012 Chris Clifton 9

Only Joe's Bar can sell beer for more than $5. beer CHAR(20), price REAL, CHECK(bar = 'Joe''s Bar' OR price <= 5.00) Spring 2012 Chris Clifton - CS54100 20 SQL Assertions Database-schema constraint. Not present in Oracle. Checked whenever a mentioned relation changes. Syntax: CREATE ASSERTION < name> CHECK(<condition> Spring 2012 Chris Clifton - CS54100 21 2012 Chris Clifton 10

No bar may charge an average of more than $5 for beer. Sells(bar, beer, price) CREATE ASSERTION NoRipoffBars CHECK(NOT EXISTS( SELECT bar FROM Sells GROUP BY bar HAVING 5.0 < AVG(price) ) Checked whenever Sells changes. Spring 2012 Chris Clifton - CS54100 22 There cannot be more bars than drinkers. Bars(name, addr, license) Drinkers(name, addr, phone) CREATE ASSERTION FewBar CHECK( (SELECT COUNT(*) FROM Bars) <= (SELECT COUNT(*) FROM Drinkers) Checked whenever Bars or Drinkers changes. Spring 2012 Chris Clifton - CS54100 23 2012 Chris Clifton 11

Triggers (Oracle Version) Often called event-condition-action rules. Event = a class of changes in the DB, e.g., insertions into Beers. Condition = a test as in a where-clause for whether or not the trigger applies. Action = one or more SQL statements. Differ from checks or SQL assertions in that: 1. Triggers invoked by the event; the system doesn t have to figure out when a trigger could be violated. 2. Condition not available in checks. Spring 2012 Chris Clifton - CS54100 24 Whenever we insert a new tuple into Sells, make sure the beer mentioned is also mentioned in Beers, and insert it (with a null manufacturer) if not. Sells(bar, beer, price) CREATE OR REPLACE TRIGGER BeerTrig AFTER INSERT ON Sells FOR EACH ROW WHEN(new.beer NOT IN (SELECT name FROM Beers)) BEGIN INSERT INTO Beers(name) VALUES(:new.beer END;. run Spring 2012 Chris Clifton - CS54100 25 2012 Chris Clifton 12

Options 1. Can omit OR REPLACE. But if you do, it is an error if a trigger of this name exists. 2. AFTER can be BEFORE. 3. If the relation is a view, AFTER can be INSTEAD OF. Useful for allowing modifications to a view; you modify the underlying relations instead. 4. INSERT can be DELETE or UPDATE OF <attribute>. Also, several conditions like INSERT ON Sells can be connected by OR. 5. FOR EACH ROW can be omitted, with an important effect: the action is done once for the relation(s) consisting of all changes. Spring 2012 Chris Clifton - CS54100 26 Notes There are two special variables new and old, representing the new and old tuple in the change. old makes no sense in an insert, and new makes no sense in a delete. Notice: in WHEN we use new and old without a colon, but in actions, a preceding colon is needed. The action is a PL/SQL statement. Simplest form: surround one or more SQL statements with BEGIN and END. However, select-from-where has a limited form. Spring 2012 Chris Clifton - CS54100 27 2012 Chris Clifton 13

Triggers are part of the database schema, like tables or views. Important Oracle constraint: the action cannot change the relation that triggers the action. Worse, the action cannot even change a relation connected to the triggering relation by a constraint, e.g., a foreign-key constraint. Spring 2012 Chris Clifton - CS54100 28 Maintain a list of all the bars that raise their price for some beer by more than $1. Sells(bar, beer, price) RipoffBars(bar) CREATE TRIGGER PriceTrig AFTER UPDATE OF price ON Sells FOR EACH ROW WHEN(new.price > old.price + 1.00) BEGIN INSERT INTO RipoffBars VALUES(:new.bar END;. run Spring 2012 Chris Clifton - CS54100 29 2012 Chris Clifton 14