SQL Constraints and Triggers

Similar documents
Basic SQL. Dr Paolo Guagliardo. University of Edinburgh. Fall 2016

CS W Introduction to Databases Spring Computer Science Department Columbia University

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

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

SQL DATA DEFINITION LANGUAGE

Nested Queries. Dr Paolo Guagliardo. Aggregate results in WHERE The right way. Fall 2018

Integrity and Security

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

Domain Constraints Referential Integrity Assertions Triggers. Authorization Authorization in SQL

SQL DATA DEFINITION LANGUAGE

Introduction to Data Management CSE 344

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

Chapter 8 INTEGRITY 1

A database consists of several tables (relations) AccountNum

SQL: Data Definition Language

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

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

CS2300: File Structures and Introduction to Database Systems

Data Modelling and Databases. Exercise Session 7: Integrity Constraints

Full file at

BASIC SQL CHAPTER 4 (6/E) CHAPTER 8 (5/E)

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

BASIC SQL CHAPTER 4 (6/E) CHAPTER 8 (5/E)

SQL DATA DEFINITION LANGUAGE

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

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

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

2.9 Table Creation. CREATE TABLE TableName ( AttrName AttrType, AttrName AttrType,... )

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

Constraints. Local and Global Constraints Triggers

Oracle Create Table Foreign Key On Delete No

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

COMP102: Introduction to Databases, 20

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

Relational Model, Key Constraints

Introduction to Data Management CSE 344

EGCI 321: Database Systems. Dr. Tanasanee Phienthrakul

Basic SQL. Basic SQL. Basic SQL

CS54100: Database Systems

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

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

Chapter 5. The Relational Data Model and Relational Database Constraints. Slide 5-١. Copyright 2007 Ramez Elmasri and Shamkant B.

Copyright 2007 Ramez Elmasri and Shamkant B. Navathe. Slide 5-1

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

The Relational Data Model and Relational Database Constraints

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

Relational Model History. COSC 304 Introduction to Database Systems. Relational Model and Algebra. Relational Model Definitions.

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

3ISY402 DATABASE SYSTEMS

Introduction to Database Systems CSE 414

Constraints and Triggers

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

Data Manipulation (DML) and Data Definition (DDL)

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

PostgreSQL 7.3 Documentation Prev Chapter 2. Data Definition Next

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

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

Database Systems Relational Model. A.R. Hurson 323 CS Building

CSE 132A Database Systems Principles

DATABASDESIGN FÖR INGENJÖRER - 1DL124

Chapter 5. Relational Model Concepts 5/2/2008. Chapter Outline. Relational Database Constraints

Chapter 5. Relational Model Concepts 9/4/2012. Chapter Outline. The Relational Data Model and Relational Database Constraints

The Relational Model of Data (ii)

SQL Fundamentals. Chapter 3. Class 03: SQL Fundamentals 1

Database Management System (15ECSC208) UNIT I: Chapter 2: Relational Data Model and Relational Algebra

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

Database Management Systems Triggers

CSE 344 AUGUST 1 ST ENTITIES

Chapter 1 SQL and Data

01/01/2017. Chapter 5: The Relational Data Model and Relational Database Constraints: Outline. Chapter 5: Relational Database Constraints

COSC344 Database Theory and Applications. Lecture 5 SQL - Data Definition Language. COSC344 Lecture 5 1

Integrity Constraints (Reminder)

Introduction to Data Management CSE 344

SQL and Incomp?ete Data

SQL functions fit into two broad categories: Data definition language Data manipulation language

CONSTRAINTS AND UPDATES CHAPTER 3 (6/E) CHAPTER 5 (5/E)

Module 9: Managing Schema Objects

Database System Concepts

Overview. Data Integrity. Three basic types of data integrity. Integrity implementation and enforcement. Database constraints Transaction Trigger

The Relational Model 2. Week 3

CHAPTER4 CONSTRAINTS

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

Slides by: Ms. Shree Jaswal

Basic SQL. Dr Fawaz Alarfaj. ACKNOWLEDGEMENT Slides are adopted from: Elmasri & Navathe, Fundamentals of Database Systems MySQL Documentation

CS121 MIDTERM REVIEW. CS121: Relational Databases Fall 2017 Lecture 13

Enhanced Data Models for Advanced Applications. Active Database Concepts

SQL DDL. CS3 Database Systems Weeks 4-5 SQL DDL Database design. Key Constraints. Inclusion Constraints

Database Systems: Design, Implementation, and Management Tenth Edition. Chapter 7 Introduction to Structured Query Language (SQL)

Views, assertions, and triggers

Relational model continued. Understanding how to use the relational model. Summary of board example: with Copies as weak entity

Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5-1

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

DATABASE DESIGN - 1DL400

The Basic (Flat) Relational Model. Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

CSE 344 JULY 30 TH DB DESIGN (CH 4)

SQL: A COMMERCIAL DATABASE LANGUAGE. Complex Constraints

Sankalchand Patel College of Engineering, Visnagar B.E. Semester III (CE/IT) Database Management System Question Bank / Assignment

Lecture 07. Spring 2018 Borough of Manhattan Community College

Intermediate SQL ( )

SQL: Queries, Constraints, Triggers (iii)

Transcription:

SQL Constraints and Triggers Dr Paolo Guagliardo University of Edinburgh Fall 2016 This page is intentionally left blank

Basic SQL constraints We have already seen: UNIQUE to declare keys NOT NULL to disallow null values PRIMARY KEY key + not null FOREIGN KEY to reference attributes in other tables NULL values are ignored when checking constraints except for NOT NULL and PRIMARY KEY Keys CREATE TABLE Account ( accnum VARCHAR(12) UNIQUE, branch VARCHAR(30), custid VARCHAR(10), balance NUMERIC(14,2) The following insertion gives an error: INSERT INTO Account VALUES (1, London, cust1, 100), (1, Edinburgh, cust3, 200 The following insertion succeeds: INSERT INTO Account VALUES (NULL, London, cust1, 100), (NULL, Edinburgh, cust3, 200

Compound keys Keys consisting of more than one attribute must be declared using a different syntax CREATE TABLE Movies ( m_title VARCHAR(30), m_director VARCHAR(30), m_year SMALLINT, m_genre VARCHAR(30), UNIQUE (m_title,m_year) This declares the set {m title,m year} as a key for Movies Primary Keys Essentially UNIQUE + NOT NULL CREATE TABLE Account ( accnum VARCHAR(12) PRIMARY KEY, branch VARCHAR(30), custid VARCHAR(10), balance NUMERIC(14,2) same as CREATE TABLE Account ( accnum VARCHAR(12) NOT NULL UNIQUE, branch VARCHAR(30), custid VARCHAR(10), balance NUMERIC(14,2)

Foreign keys in SQL (1) CREATE TABLE Customer ( custid VARCHAR(10) PRIMARY KEY name VARCHAR(20), city VARCHAR(30), address VARCHAR(30) CREATE TABLE Account ( accnum VARCHAR(12), branch VARCHAR(30), custid VARCHAR(10) REFERENCES Customer(custid), balance NUMERIC(14,2) Every value for attribute custid in Account must appear among the values of the key custid in Customer Foreign keys in SQL (2) General syntax (useful for declaring compound foreign keys) CREATE TABLE <table1> ( <attr> <type>,... <attr> <type>, FOREIGN KEY (<list1>) REFERENCES <table2>(<list2>) where <list1> and <list2> are lists with the same number of attributes attributes in <list1> are from table <table1> attributes in <list2> are unique in <table2>

Referential integrity and database modifications (1) Deletion can cause problems with foreign keys Customer ID Name cust1 John cust2 Mary Account Number CustID 123456 cust1 654321 cust2 where Account.CustID is a foreign key for Customer.ID What happens if one deletes (cust1,john) from Customer? Three approaches are supported in SQL: 1. Reject the deletion operation 2. Propagate it to Account by deleting also (123456,cust1) 3. Don t know approach: keep the tuple in Account, but set CustID value to NULL Referential integrity and database modifications (2) All three approaches are supported in SQL CREATE TABLE <table1> ( <attr> <type>,... FOREIGN KEY <list1> REFERENCES <table2>(<list2>) <approach> ) where <approach> can be: 1. Empty: Reject deletions from <table2> causing the FK to be violated (this is the default when <approach> is not specified) 2. ON DELETE CASCADE: Propagate the deletion to <name> (tuples in <table1> that violate the FK will be deleted) 3. ON DELETE SET NULL: Don t know approach (the values of the attributes in <list1>, for tuples in <name> that violate the FK, are set to NULL)

Check constraints (1) Syntax: CHECK ( conditional-expression ) Update/insertion is rejected if the condition evaluates to false Example CREATE TABLE Products ( pcode INTEGER PRIMARY KEY, pname VARCHAR(10), pdesc VARCHAR(20), ptype VARCHAR(20), price NUMERIC(6,2) CHECK ( price > 0 ), CHECK ( ptype IN ( BOOK, MOVIE, MUSIC ) ) Check constraints (2) Another example CREATE TABLE Invoices ( invid INTEGER PRIMARY KEY, ordid INTEGER NOT NULL UNIQUE, amount NUMERIC(8,2) CHECK ( amount > 0 ), issued DATE, due DATE, CHECK ( ordid IN SELECT ordid FROM Orders ), CHECK ( due >= issued ) The check on ordid is similar to a foreign key, but not the same SQL allows queries in CHECK (not implemented in PostgreSQL)

Domain constraints (1) A domain is essentially a data type with optional constraints Syntax CREATE DOMAIN name datatype [ DEFAULT value ] [ constraint ] where constraint is NOT NULL CHECK ( expression ) In CHECK expression, VALUE refers to the value being tested Example CREATE DOMAIN posnumber NUMERIC(10,2) CHECK ( VALUE > 0 CREATE DOMAIN category VARCHAR(20) CHECK ( VALUE IN ( BOOK, MUSIC, MOVIE ) Domain constraints (2) CREATE TABLE Products ( pcode INTEGER PRIMARY KEY, pname VARCHAR(10), pdesc VARCHAR(20), ptype category, price posnumber CREATE TABLE Invoices ( invid INTEGER PRIMARY KEY, ordid INTEGER NOT NULL UNIQUE, amount posnumber, issued DATE, due DATE, CHECK ( ordid IN SELECT ordid FROM Orders ), CHECK ( due >= issued )

Assertions Essentially a CHECK constraint not bound to a specific table Syntax: CREATE ASSERTION name CHECK ( condition ) Example CREATE ASSERTION too_many_customers CHECK ( ( SELECT COUNT(*) FROM customers ) <= 1000 ) ; Standard SQL Not implemented in any of the currently available DBMSs The problem is allowing queries in CHECK Triggers Specify an action to execute if certain events took place Event: a change to the database that activates the trigger (an insertion, a deletion, or an update) Condition: a query or test checked when the trigger is activated (for a query: empty is false, non-empty is true) Action: a procedure executed when the condition is true can refer to old/new values of modified tuples can examine answers to the condition query can execute new queries can make changes to the database (both data and schema) can be executed before/after the event for each row or for each statement

Triggers: Example 1 Suppose we have Products : pcode, pname, price Orders : ordid, odate, ocust, final (bool) Details : ordid, pcode, qty Prices : ordid, pcode, price Whenever a new detail for an order is inserted we want to save the price of the corresponding products Triggers: Example 1 CREATE TRIGGER save_price AFTER INSERT ON details REFERENCING NEW TABLE AS inserted FOR EACH STATEMENT WHEN TRUE BEGIN INSERT INTO prices(ordid,pcode,price) SELECT I.ordid, I.pcode, P.price FROM inserted I JOIN products P ON I.pcode = P.pcode END ;

Triggers: Example 2 Suppose we have Products : pcode, pname, price Orders : ordid, odate, ocust, final (bool) Details : ordid, pcode, qty Prices : ordid, pcode, price Invoices : invid (serial), ordid, amount, issued, due Whenever an order becomes final we want to generate an invoice for it Triggers: Example 2 CREATE TRIGGER invoice_order AFTER UPDATE OF final ON orders REFERENCING OLD ROW AS oldrow NEW ROW AS newrow FOR EACH ROW WHEN oldrow.final = FALSE AND newrow.final = TRUE BEGIN INSERT INTO invoices(ordid,amount,issued,due) SELECT O.ordid, SUM(D.qty * P.price), O.odate, O.odate+7d FROM orders O, details D, prices P WHERE O.ordid = newrow.ordid AND O.ordid = D.ordid AND D.ordid = P.ordid AND D.pcode = P.pcode END ;

Triggers in real systems In PostgreSQL (and similarly for other DBMSs): CREATE TRIGGER name { BEFORE AFTER } event ON table_name FOR EACH { ROW STATEMENT } WHEN ( condition ) EXECUTE PROCEDURE function_name ( arguments ) where event can be one of: INSERT UPDATE [ OF column [,... ] ] DELETE and condition cannot contain queries Triggers for database consistency Constraints Protection against any statement Defined declaratively easier to understand easier to optimize Triggers Activated by specific statement Defined operationally effect may be obscure more flexibility

Other uses of triggers Alert users Logging events Gather statistics Replication Workflow management Business rules enforcement Caution with triggers An event may activate more than one trigger Activated triggers are processed in some arbitrary order Actions can activate other triggers: we get a chain Recursive trigger The action directly/indirectly activates the same trigger = collections of triggers can have unpredictable effects