© 2014 Zvi M. Kedem 1 Unit 6 SQL: Data Definition Language And Data Control Language For Relational Databases.

Slides:



Advertisements
Similar presentations
Data Definition and Integrity Constraints
Advertisements

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5 More SQL: Complex Queries, Triggers, Views, and Schema Modification.
MSc IT UFCE8K-15-M Data Management Prakash Chatterjee Room 2Q18
1 Constraints, Triggers and Active Databases Chapter 9.
Relational Database. Relational database: a set of relations Relation: made up of 2 parts: − Schema : specifies the name of relations, plus name and type.
Database Management Systems, R. Ramakrishnan and J. Gehrke1 The Relational Model Chapter 3.
SQL Lecture 10 Inst: Haya Sammaneh. Example Instance of Students Relation  Cardinality = 3, degree = 5, all rows distinct.
Database Design -- Basic SQL
SQL Constraints and Triggers
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5 More SQL: Complex Queries, Triggers, Views, and Schema Modification.
Cs3431 Constraints Sections 6.1 – 6.5. cs3431 Example CREATE TABLE Student ( sNum int, sName varchar (20), prof int, CONSTRAINT pk PRIMARY KEY (snum),
CMPT 354, Simon Fraser University, Fall 2008, Martin Ester 28 Database Systems I The Relational Data Model.
Constraints and Triggers Foreign Keys Local and Global Constraints Triggers.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 3 The Basic (Flat) Relational Model.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 4 SQL: Data Definition, Constraints, and Basic Queries and Updates.
1 More SQL Defining a Database Schema Views. 2 Defining a Database Schema uA database schema comprises declarations for the relations (“tables”) of the.
1 Query Languages: How to build or interrogate a relational database Structured Query Language (SQL)
©Silberschatz, Korth and Sudarshan6.1Database System Concepts Schema Management and SQL as DDL Professor Kedem’s changes, if any, are marked in green,
1 Relational Model. 2 Relational Database: Definitions  Relational database: a set of relations  Relation: made up of 2 parts: – Instance : a table,
Database Systems More SQL Database Design -- More SQL1.
CMPT 354, Simon Fraser University, Fall 2008, Martin Ester 157 Database Systems I SQL Constraints and Triggers.
CONSTRAINTS AND UPDATES CHAPTER 3 (6/E) CHAPTER 5 (5/E) 1.
Chapter 6: Integrity and Security Thomas Nikl 19 October, 2004 CS157B.
The Relational Model These slides are based on the slides of your text book.
CSE314 Database Systems Lecture 4 Basic SQL Doç. Dr. Mehmet Göktürk src: Elmasri & Navanthe 6E Pearson Ed Slide Set.
The Relational Model. Review Why use a DBMS? OS provides RAM and disk.
CSE314 Database Systems More SQL: Complex Queries, Triggers, Views, and Schema Modification Doç. Dr. Mehmet Göktürk src: Elmasri & Navanthe 6E Pearson.
SQL data definition using Oracle1 SQL Data Definition using Oracle.
1 The Relational Model Instructor: Mohamed Eltabakh
Chapter 8 Part 1 SQL-99 Schema Definition, Constraints, Queries, and Views.
Lecture 7 Integrity & Veracity UFCE8K-15-M: Data Management.
SQL data definition using Oracle1 SQL Data Definition using Oracle.
SQL SQL Server : Overview SQL : Overview Types of SQL Database : Creation Tables : Creation & Manipulation Data : Creation & Manipulation Data : Retrieving.
FALL 2004CENG 351 File Structures and Data Management1 Relational Model Chapter 3.
SQL: DDL. SQL Statements DDL - data definition language –Defining and modifying data structures (metadata): database, tables, views, etc. DML - data manipulation.
SQL Fundamentals  SQL: Structured Query Language is a simple and powerful language used to create, access, and manipulate data and structure in the database.
IS 230Lecture 6Slide 1 Lecture 7 Advanced SQL Introduction to Database Systems IS 230 This is the instructor’s notes and student has to read the textbook.
IST 210 Constraints and Triggers. IST Constraints and Triggers Constraint: relationship among data elements DBMS should enforce the constraints.
Fall 2001Database Systems1 Triggers Assertions –Assertions describe rules that should hold for a given database. –An assertion is checked anytime a table.
Advanced SQL: Triggers & Assertions
Dec 8, 2003Murali Mani Constraints B term 2004: lecture 15.
Constraints and Triggers. What’s IC? Integrity Constraints define the valid states of SQL-data by constraining the values in the base tables. –Restrictions.
The Relational Model Content based on Chapter 3 Database Management Systems, (Third Edition), by Raghu Ramakrishnan and Johannes Gehrke. McGraw Hill, 2003.
1 CS 430 Database Theory Winter 2005 Lecture 4: Relational Model.
CSE314 Database Systems Lecture 3 The Relational Data Model and Relational Database Constraints Doç. Dr. Mehmet Göktürk src: Elmasri & Navanthe 6E Pearson.
DATA AND SCHEMA MODIFICATIONS CHAPTERS 4,5 (6/E) CHAPTER 8 (5/E) 1.
Chapter 5 : Integrity And Security  Domain Constraints  Referential Integrity  Security  Triggers  Authorization  Authorization in SQL  Views 
Week 8-9 SQL-1. SQL Components: DDL, DCL, & DML SQL is a very large and powerful language, but every type of SQL statement falls within one of three main.
CS34311 The Relational Model. cs34312 Why Relational Model? Currently the most widely used Vendors: Oracle, Microsoft, IBM Older models still used IBM’s.
Starting with Oracle SQL Plus. Today in the lab… Connect to SQL Plus – your schema. Set up two tables. Find the tables in the catalog. Insert four rows.
Constraints and Views Chap. 3-5 continued (7 th ed. 5-7)
Murali Mani Constraints. Murali Mani Keys: Primary keys and unique CREATE TABLE Student ( sNum int, sName varchar (20), dept char (2), CONSTRAINT key.
CDT/1 Creating data tables and Referential Integrity Objective –To learn about the data constraints supported by SQL2 –To be able to relate tables together.
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke1 The Relational Model Chapter 3.
1 CS122A: Introduction to Data Management Lecture #4 (E-R  Relational Translation) Instructor: Chen Li.
CENG 351 File Structures and Data Management1 Relational Model Chapter 3.
1 Constraints and Triggers in SQL. 2 Constraints are conditions that must hold on all valid relation instances SQL2 provides a variety of techniques for.
More SQL: Complex Queries, Triggers, Views, and Schema Modification
Chapter 6: Integrity (and Security)
TABLES AND INDEXES Ashima Wadhwa.
Constraints and Triggers
Active Database Concepts
Foreign Keys Local and Global Constraints Triggers
Instructor: Mohamed Eltabakh
The Relational Model Relational Data Model
SQL OVERVIEW DEFINING A SCHEMA
SQL data definition using Oracle
Advanced SQL: Views & Triggers
SQL-1 Week 8-9.
SQL – Constraints & Triggers
Presentation transcript:

© 2014 Zvi M. Kedem 1 Unit 6 SQL: Data Definition Language And Data Control Language For Relational Databases

© 2014 Zvi M. Kedem 2 DDL (and DCL) in Context

© 2014 Zvi M. Kedem 3 The Tables To Be Defined And Some More uThis is the database we will define uWe do not pay attention to domains of attributes as there is not much interesting in this

© 2014 Zvi M. Kedem 4 Defining A Relational Database uWe will only some of the basic capabilities for defining a relational database uThe standard is very extensive and provides for a rich repertoire of useful capabilities uWe can only touch on some of them uBut enough for defining reasonable-complexity databases

© 2014 Zvi M. Kedem 5 Basic Definition uCREATE TABLE Plant ( P CHAR(10), Pname CHAR VARYING(10), Pcity CHAR VARYING(10), Profit NUMBER ); uThis is a minimal definition  Name of the table  Names of the columns  Domains of the columns

© 2014 Zvi M. Kedem 6 Basic Definition uCREATE TABLE Customer ( C CHAR(10), Cname CHAR VARYING(10), Ccity CHAR VARYING(10), P CHAR(10) ); uThis is a minimal definition  Name of the table  Names of the columns  Domains of the columns

© 2014 Zvi M. Kedem 7 Basic Definition uCREATE TABLE Invoice ( I CHAR(10), Amt NUMBER, Idate DATE, C CHAR(10) ); uThis is a minimal definition  Name of the table  Names of the columns  Domains of the columns

© 2014 Zvi M. Kedem 8 Permitted Data Types (Data Domains) uSQL standard specifies permitted data types, which can be roughly grouped into several families  Integers (small or long)  Real numbers (standard or double length and with various precisions)  Character strings (fixed or variable length)  Bit strings (fixed or variable length)  Dates and times (various specifications with various time “granularity”) uSystems have different implementations and modifications of the standard

© 2014 Zvi M. Kedem 9 Notation uIn some of the slides, new concepts will be introduced uThe SQL specifications will be in red color and bold to draw attention to them

© 2014 Zvi M. Kedem 10 Minimum Specification For Plant uCREATE TABLE Plant ( P CHAR(10) NOT NULL, Pname CHAR VARYING(10), Pcity CHAR VARYING(10), Profit NUMBER, CONSTRAINT C_20 PRIMARY KEY (P), CONSTRAINT C_30 UNIQUE (Pcity, Profit), CONSTRAINT C_40 CHECK ( Pcity <> Pname ), CONSTRAINT C_50 CHECK ( (Pcity <> 'Chicago') OR (Profit > 1000) ) ); uThis is a minimal definition  Name of the table  Names of the columns  Domains of the columns

© 2014 Zvi M. Kedem 11 Not Null uCREATE TABLE Plant ( P CHAR(10) NOT NULL, Pname CHAR VARYING(10), Pcity CHAR VARYING(10), Profit NUMBER, CONSTRAINT C_20 PRIMARY KEY (P), CONSTRAINT C_30 UNIQUE (Pcity, Profit), CONSTRAINT C_40 CHECK ( Pcity <> Pname ), CONSTRAINT C_50 CHECK ( (Pcity <> 'Chicago') OR (Profit > 1000) ) ); uSpecifies that the values in these columns (could be more than one such column) must not be NULL

© 2014 Zvi M. Kedem 12 Constraints uCREATE TABLE Plant ( P CHAR(10) NOT NULL, Pname CHAR VARYING(10), Pcity CHAR VARYING(10), Profit NUMBER, CONSTRAINT C_20 PRIMARY KEY (P), CONSTRAINT C_30 UNIQUE (Pcity, Profit), CONSTRAINT C_40 CHECK ( Pcity <> Pname ), CONSTRAINT C_50 CHECK ( (Pcity <> 'Chicago') OR (Profit > 1000) ) ); uSome constraint on the tables  Constraint name, here C_20, is not required, but it is a very good idea to give unique names to a constraint, so it can be later DROPPed or ALTERed by referring to it by its name  Constraint name should reflect something about the constraint, to save space I used short names

© 2014 Zvi M. Kedem 13 Primary Key uCREATE TABLE Plant ( P CHAR(10) NOT NULL, Pname CHAR VARYING(10), Pcity CHAR VARYING(10), Profit NUMBER, CONSTRAINT C_20 PRIMARY KEY (P), CONSTRAINT C_30 UNIQUE (Pcity, Profit), CONSTRAINT C_40 CHECK ( Pcity <> Pname ), CONSTRAINT C_50 CHECK ( (Pcity <> 'Chicago') OR (Profit > 1000) ) ); uThe column P is the primary key (only one possible)  This requires that it must not be NULL (this is not necessary to state in some systems, as the primary key condition automatically forces it by SQL standard) uPrimary key could be several columns, e.g., PRIMARY KEY(Pcity, Profit); but not in our example

© 2014 Zvi M. Kedem 14 Unique uCREATE TABLE Plant ( P CHAR(10) NOT NULL, Pname CHAR VARYING(10), Pcity CHAR VARYING(10), Profit NUMBER, CONSTRAINT C_20 PRIMARY KEY (P), CONSTRAINT C_30 UNIQUE (Pcity, Profit), CONSTRAINT C_40 CHECK ( Pcity <> Pname ), CONSTRAINT C_50 CHECK ( (Pcity <> 'Chicago') OR (Profit > 1000) ) ); uThe “subtuple” PCITY,PNAME is a candidate key  There is no requirement, in general, about any of its column being not NULL  To reiterate: all the columns of the primary key must not be NULL

© 2014 Zvi M. Kedem 15 Check (and Unknown) uCREATE TABLE Plant ( P CHAR(10) NOT NULL, Pname CHAR VARYING(10), Pcity CHAR VARYING(10), Profit NUMBER, CONSTRAINT C_20 PRIMARY KEY (P), CONSTRAINT C_30 UNIQUE (Pcity, Profit), CONSTRAINT C_40 CHECK ( Pcity <> Pname ), CONSTRAINT C_50 CHECK ( (Pcity <> 'Chicago') OR (Profit > 1000) ) ); uEvery tuple must satisfy this condition uThe condition is satisfied, when it is either  TRUE, or  UNKNOWN (so if Pcity is Null, this condition is satisfied) uRecall in SQL SELECT queries: UNKNOWN implies FALSE

© 2014 Zvi M. Kedem 16 Check uCREATE TABLE Plant ( P CHAR(10) NOT NULL, Pname CHAR VARYING(10), Pcity CHAR VARYING(10), Profit NUMBER, CONSTRAINT C_20 PRIMARY KEY (P), CONSTRAINT C_30 UNIQUE (Pcity, Profit), CONSTRAINT C_40 CHECK ( Pcity <> Pname ), CONSTRAINT C_50 CHECK ( (Pcity <> 'Chicago') OR (Profit > 1000) ) ); uThis is: (Pcity = 'Chicago')  (Profit > 1000) By standard rules of Boolean operators (propositional calculus)

© 2014 Zvi M. Kedem 17 Check (and Unknown) uCREATE TABLE Plant ( P CHAR(10) NOT NULL, Pname CHAR VARYING(10), Pcity CHAR VARYING(10), Profit NUMBER, CONSTRAINT C_20 PRIMARY KEY (P), CONSTRAINT C_30 UNIQUE (Pcity, Profit), CONSTRAINT C_40 CHECK ( Pcity <> Pname ), CONSTRAINT C_50 CHECK ( (Pcity <> 'Chicago') OR (Profit > 1000) ) ); uReturning to semantics of UNKNOWN and OR, this constraint has to evaluate to TRUE or UNKNOWN to be satisfied, so we need ( Pcity is not Chicago or IS NULL) or ( Profit is greater than 1000 or IS NULL) uSo for Chicago the profit is greater than 1000 or IS NULL

© 2014 Zvi M. Kedem 18 Defaults uCREATE TABLE Customer ( C CHAR(10) NOT NULL, Cname CHAR VARYING(10) DEFAULT (NULL), Ccity CHAR VARYING(10), P CHAR(10) DEFAULT ('Main'), CONSTRAINT C_60 PRIMARY KEY (C), CONSTRAINT C_70 FOREIGN KEY (P) REFERENCES Plant ON DELETE SET NULL ); uIt is possible to specify defaults  E.g., when a tuple is inserted and only C and Ccity are specified, the system knows to specify NULL for Cname and Main for P

© 2014 Zvi M. Kedem 19 Foreign Key uCREATE TABLE Customer ( C CHAR(10) NOT NULL, Cname CHAR VARYING(10) DEFAULT (NULL), Ccity CHAR VARYING(10), P CHAR(10) DEFAULT ('Main'), CONSTRAINT C_60 PRIMARY KEY (C), CONSTRAINT C_70 FOREIGN KEY (P) REFERENCES Plant ON DELETE SET NULL ); uP in Customer has to reference the primary key of Plant uThis means that one of two conditions is satisfied  P has a non NULL value and this value of P appears in Plant  P is NULL Of course, if P were specified as NOT NULL, this could not be the case

© 2014 Zvi M. Kedem 20 On Delete Set Null uCREATE TABLE Customer ( C CHAR(10) NOT NULL, Cname CHAR VARYING(10) DEFAULT (NULL), Ccity CHAR VARYING(10), P CHAR(10) DEFAULT ('Main'), CONSTRAINT C_60 PRIMARY KEY (C), CONSTRAINT C_70 FOREIGN KEY (P) REFERENCES Plant ON DELETE SET NULL ); uP in Customer has to reference the primary key of Plant uBut note, that P in Customer is not required to be NOT NULL uWe have a specification that if P is listed in some tuple of Customer is deleted from Plant (that is the tuple with this value of primary key is deleted), then that value of P in Plant is automatically replaced by NULL

© 2014 Zvi M. Kedem 21 Not Null uCREATE TABLE Invoice ( I CHAR(10) NOT NULL, Amt NUMBER, Idate DATE, C CHAR(10) NOT NULL, CONSTRAINT C_80 PRIMARY KEY (I), CONSTRAINT C_90 FOREIGN KEY (C) REFERENCES Customer ON DELETE CASCADE ); uNOT NULL can be specified also for columns not in the primary key

© 2014 Zvi M. Kedem 22 On Delete Cascade uCREATE TABLE Invoice ( I CHAR(10) NOT NULL, Amt NUMBER, Idate DATE, C CHAR(10) NOT NULL, CONSTRAINT C_80 PRIMARY KEY (I), CONSTRAINT C_90 FOREIGN KEY (C) REFERENCES Customer ON DELETE CASCADE ); uWe have a specification that if C listed in some tuple of Invoice is deleted from Customer (that is the tuple with this value of primary key is deleted), all the tuples with this value of C in Invoice must be deleted

© 2014 Zvi M. Kedem 23 Maintenance of Referential Integrity uIn order to maintain referential integrity constraints, the system will reject any operation that will violate it.  There are subtle interactions if NULLs are present; we will not discuss them here uCREATE TABLE Invoice ( I CHAR(10) NOT NULL, Amt NUMBER, Idate DATE, C CHAR(10) NOT NULL, CONSTRAINT C_80 PRIMARY KEY (I), CONSTRAINT C_90 FOREIGN KEY (C) REFERENCES Customer ON... );

© 2014 Zvi M. Kedem 24 Maintenance of Referential Integrity On Update uThis constraint “will act” when:  An INSERT or an UPDATE on Invoice is attempted that would produce there a value of of C that does not exist in Customer.  A DELETE or an UPDATE on Customer is attempted that will leave tuples in Invoice in which the value of C does not appear in any tuple of Customer. uThe default is NO ACTION, that is the above will not be permitted uWe will briefly discuss other options in case of UPDATEs of Customer and skip what happens in other cases  CASCADE: the new value of the primary key is copied to the foreign key  SET NULL: the new value of the foreign key is NULL  SET DEFAULT: the new value of the foreign key is a specified default value (which of course has to appear in Customer)

© 2014 Zvi M. Kedem 25 Starting With A Basic Definition uIt is generally a good idea to start with a basic definition and augment it with constraints later uWe see how this is done

© 2014 Zvi M. Kedem 26 Basic Definition uCREATE TABLE Plant ( P CHAR(10) NOT NULL, Pname CHAR VARYING(10), Pcity CHAR VARYING(10), Profit NUMBER );

© 2014 Zvi M. Kedem 27 Basic Definition uCREATE TABLE Customer ( C CHAR(10) NOT NULL, Cname CHAR VARYING(10) DEFAULT (NULL), Ccity CHAR VARYING(10), P CHAR(10) DEFAULT ('Main') );

© 2014 Zvi M. Kedem 28 Basic Definition uCREATE TABLE Invoice ( I CHAR(10) NOT NULL, Amt NUMBER, Idate DATE, C CHAR(10) NOT NULL );

© 2014 Zvi M. Kedem 29 Altering The Definition To Add Constraints uALTER TABLE Plant ADD CONSTRAINT C_20 PRIMARY KEY (P); uALTER TABLE Customer ADD CONSTRAINT C_60 PRIMARY KEY (C); uALTER TABLE Invoice ADD CONSTRAINT C_80 PRIMARY KEY (I); uALTER TABLE Customer ADD CONSTRAINT C_70 FOREIGN KEY (P) REFERENCES Plant ON DELETE SET NULL; uALTER TABLE Invoice ADD CONSTRAINT C_90 FOREIGN KEY (C) REFERENCES Customer ON DELETE CASCADE;

© 2014 Zvi M. Kedem 30 Altering The Definition To Add Constraints uALTER TABLE Plant ADD CONSTRAINT C_30 UNIQUE (Pcity, Profit); uALTER TABLE Plant ADD CONSTRAINT C_40 CHECK ( Pcity <> Pname ); uALTER TABLE Plant ADD CONSTRAINT C_50 CHECK ( (Pcity <> 'Chicago') OR (Profit > 1000) );

© 2014 Zvi M. Kedem 31 FOREIGN KEY Can Reference The Table Itself uWe store information about women uWith each woman, we store her mother, if the mother is known uOf course, the mother is a woman ucreate table WOMAN ( SSN CHAR(9) not null, NAME CHAR VARYING(10) default (null), MOTHER CHAR(9) default (null) ); ualter table WOMAN add constraint C_01 primary key (SSN); alter table WOMAN add constraint C_02 foreign key (MOTHER) references WOMAN;

© 2014 Zvi M. Kedem 32 Referencing Unique uForeign key can also refer to UNIQUE and not only to PRIMARY KEY uSo we could also add to our database such a constraint, for which we look at an example uCREATE TABLE Test ( TestID CHAR(10) NOT NULL, TestPname CHAR VARYING(10), TestPcity CHAR VARYING(10), TestProfit NUMBER ); uALTER TABLE Test ADD CONSTRAINT C_99 FOREIGN KEY (TestPcity, TestProfit) REFERENCES Plant(Pcity, Profit);

© 2014 Zvi M. Kedem 33 Sometimes It Is Necessary To Define Tables First And Then Add Constraints uIf you define a foreign key constraint, it cannot refer to a table that has not yet been designed uConsider the following Visio diagram uYou have “circular” dependencies  You cannot fully define Husband before Wife  You cannot fully define Wife before Husband uTherefore 1.Produce basic definitions for Husband and Wife 2.Alter them by adding constraints later

© 2014 Zvi M. Kedem 34 UNIQUE and PRIMARY KEY uBack to our old example uCREATE TABLE City Country NOT NULL, State, Name NOT NULL, Longitude NOT NULL, Latitude NOT NULL ); uA city can be identified in one of two ways  By its geographic location: Longitude and Latitude  By its official “hierarchy of names”: Country, State, Name uIt may be the case that some countries are not divided into states (or equivalent units)  For them it is natural to allow State to be NULL, as opposed to faking something

© 2014 Zvi M. Kedem 35 UNIQUE and PRIMARY KEY uThe following is OK uCREATE TABLE City Country NOT NULL, State, Name NOT NULL, Longitude NOT NULL, Latitude NOT NULL, UNIQUE (Country, State, Name), PRIMARY KEY (Longitude, Latitude) );

© 2014 Zvi M. Kedem 36 UNIQUE and PRIMARY KEY uThe following is not OK uCREATE TABLE City Country NOT NULL, State, Name NOT NULL, Longitude NOT NULL, Latitude NOT NULL, PRIMARY KEY (Country, State, Name), UNIQUE (Longitude, Latitude) ); uBecause State could be NULL, not permitted in primary key uWe will see why primary keys should not contain NULLs (there are other reasons for this too)

© 2014 Zvi M. Kedem 37 UNIQUE and PRIMARY KEY uSmall database  CREATE TABLE City_Population Country NOT NULL, State, Name NOT NULL, Longitude NOT NULL, Latitude NOT NULL, Population, PRIMARY KEY (Country, State, Name), UNIQUE (Longitude, Latitude) );  CREATE TABLE City_Size Country NOT NULL, State, Name NOT NULL, Longitude NOT NULL, Latitude NOT NULL, Size, PRIMARY KEY (Country, State, Name), UNIQUE (Longitude, Latitude) );

© 2014 Zvi M. Kedem 38 UNIQUE and PRIMARY KEY uWe want to combine information about cities from both tables uSELECT * FROM City_Population, City_Size WHERE (City_Population.Country = City_Size.Country AND City_Population.State = City_Size.State AND City_Population.Name = City_Size.Name) ; uWe will not get anything for cities in countries that are not divided into states! uBecause the result of comparison of say (Monaco, NULL, Monaco-Ville) = (Monaco, NULL, Monaco-Ville) is UNKNOWN uTherefore, we cannot have (Country,State,Name) as PRIMARY KEY

© 2014 Zvi M. Kedem 39 Workaround uThe following can be done if we want to use UNIQUE set of attributes for joining in our example uSELECT * FROM City_Population, City_Size WHERE City_Population.Country = City_Size.Country AND City_Population.Name = City_Size.Name AND ( City_Population.State = City_Size.State OR (City_Population.State IS NULL AND City_Size.State IS NULL ) ); uBut this is very burdensome and potentially easily forgotten

© 2014 Zvi M. Kedem 40 When Are Constraints Checked? uEssentially, each row of the TABLE has to satisfy the constraint uConstraints are checked as tables are modified (immediately or deferred until later, generally until the end of a transaction) uThe actual checking is done either after each statement or at the end of a transaction  It is done at the end, to allow changes that cannot be done in a single statement  For example if Total = Checking + Savings and money is moved from Checking to Savings this constraint could be violated in the middle of the move, but must be satisfied before and after the move uSo as part of specification of a constraint one can specify  NOT DEFERRABLE (this is the default), or  DEFERRABLE

© 2014 Zvi M. Kedem 41 Assertions uAssertion is like a CHECK constraint, but it is not attached to a TABLE definition; it is “free floating” uCREATE ASSERTION Assertion01 CHECK ( (SELECT COUNT (*) FROM Plant) + (SELECT COUNT (*) FROM Customer) < 1000 ); uAssertions are more natural than previously described constraints, especially when referring to several tables uHowever, they are frequently not implemented, e.g., Oracle uIt is very difficult to implement them both correctly and efficiently

© 2014 Zvi M. Kedem 42 Example on UNKNOWN Using Oracle uWe define a table and insert tuples into it uOur second tuple is interesting  For DDL and DML INSERT it satisfies the constraint (actually UNKNOWN)  For DML SELECT it does not satisfy the constraint (actually UNKNOWN) create table TEST_UNKNOWN ( X CHAR VARYING(10), Y CHAR VARYING(10), check (X=Y) ); Insert into TEST_UNKNOWN values('a','a'); Insert into TEST_UNKNOWN values('b',null); Insert into TEST_UNKNOWN values('c','d');

© 2014 Zvi M. Kedem 43 Example on UNKNOWN Using Oracle Table created. 1 row created. Insert into TEST_UNKNOWN values('c','d') * ERROR at line 1: ORA-02290: check constraint (KEDEM.SYS_C ) violated u Note that the third tuple does not satisfy the constraint for DDL

© 2014 Zvi M. Kedem 44 Example on UNKNOWN Using Oracle select * from TEST_UNKNOWN; X Y a b uThe table has two tuples

© 2014 Zvi M. Kedem 45 Example on UNKNOWN Using Oracle select * from TEST_UNKNOWN where x=y; X Y a u One tuple is output

© 2014 Zvi M. Kedem 46 Views uWe now proceed to the definition of the user level, that is to the definition of views uGenerally speaking, a view consists of “continuously current” table that is derived by means of a SELECT statement from other tables uFor example, we could write CREATE VIEW GoodPlant AS SELECT * FROM Plant WHERE Profit >.0; uWe could now execute a query against the view SELECT P FROM GoodPlant WHERE City = 'Chicago'; uThis will give all P for Chicago where Profit is positive

© 2014 Zvi M. Kedem 47 Views Versus Snapshots uView is not a snapshot, which is static uView can be thought of as a procedure call uTherefore we should think of the following procedure for computing the answer to the last query: uThe system computes the value of the table GoodPlant uThe system executes the query against the table GoodPlant uIn actuality, the system may compute the answer differently, however, the result will be equivalent to the canonical procedure described above

© 2014 Zvi M. Kedem 48 Views Defined by Queries uIn general, almost any query definition could be used to define a view, so we could have: CREATE VIEW Customer_In_The_City AS SELECT Cname FROM Plant, Customer WHERE Pcity = Ccity AND Plant.C = Customer.C; uViews can also be defined WITH CHECK OPTION, which we will discuss later.

© 2014 Zvi M. Kedem 49 Updating Views uViews, in principle, can be updated just like the base tables uHowever, all updates to views must be reflected in a correct update to the base table. uLet us start with the view CREATE VIEW GoodPlant AS SELECT * FROM Plant WHERE Profit > 0.0; uThen, it is clear what should be inserted into the table Plant if the following is issued: INSERT INTO GoodPlant VALUES (675, 'Major', 'Philadelphia',.25);

© 2014 Zvi M. Kedem 50 Updating Views While Forcing Defaults uConsider now the view CREATE VIEW SomePlant AS SELECT P, Pname, City FROM Plant; uThen, if the value of Profit can be NULL or has a defined default value, it is clear what should be inserted into the table Plant if the following is issued: INSERT INTO SomePlant VALUES (675, 'Major', 'Philadelphia');

© 2014 Zvi M. Kedem 51 Update To View Not Reflected In It uConsider the view CREATE VIEW Plant_In_Chicago AS SELECT * FROM Plant WHERE City = 'Chicago'; uAccording to SQL the following update is valid INSERT INTO Plant_In_Chicago VALUES (897,'Minor','Philadelphia',.1); uIt is reflected properly in the base table Plant, however, it does not show in the view, of course

© 2014 Zvi M. Kedem 52 Checking for Updates Not Reflected in View uInstead, if we define the view CREATE VIEW Plant_In_Chicago AS SELECT * FROM Plant WHERE City = 'Chicago' WITH CHECK OPTION; uThen the update INSERT INTO Plant_In_Chicago VALUES (897,'Minor','Philadelphia',.1); will be rejected

© 2014 Zvi M. Kedem 53 Some Views Cannot Be Updated uConsider the view CREATE VIEW Profit_On_Date AS SELECT Profit, Date FROM Plant, Invoice, Customer WHERE Plant.P = Customer.P AND Invoice.C = Customer.C; uThere is no meaning to the update INSERT INTO Profit_On_Date VALUES (0.9, ); uWhy?  Because there is no well-defined way for reflecting this update in the base tables  Several tables would need to be modified in a non-deterministic fashion

© 2014 Zvi M. Kedem 54 Some Views That Cannot Be Updated uConsider the view CREATE VIEW Avg_Amt AS SELECT AVG(Amt) FROM Invoice WHERE Idate = ‘ ’; uIt is not permitted to issue: INSERT INTO Avg_Amt VALUES (75);  There is no way of changing the base tables in a well-defined way.

© 2014 Zvi M. Kedem 55 Some Views That Cannot Be Updated uConsider the view CREATE VIEW Cities_With_Plant AS SELECT Pcity FROM Plant; uIt is not permitted to issue INSERT INTO Cities_With_Plant VALUES ('Palm Beach');  P cannot have a NULL value, as it was the primary key

© 2014 Zvi M. Kedem 56 Views That Are Updateable In Standard SQL uThe following are the major conditions (there are others) that must be true for an updatable view  Is drawn from one TABLE No joins, unions, differences, intersections  If the underlying TABLE is a view, it must be updateable  The SELECTed columns are column references (each column at most once and without DISTINCT) and not values or aggregates  No GROUP BY

© 2014 Zvi M. Kedem 57 Some Views That Should Be Updateable uIt may make sense to update views that the SQL standard does not allow to update and it is now sometimes permissible; that is, in some implementations uIf we have two tables  R(SSN, Salary)  S(SSN, Address) uConsider the view CREATE VIEW RS AS SELECT R.SSN AS SSN, Salary, Address FROM R, S WHERE R.SSN = S.SSN ; uAnd it is perfectly clear what to do if a new employee is inserted into RS: i.e., how to reflect this in R and in S

© 2014 Zvi M. Kedem 58 Updating Views uSQL prohibits this uBut Oracle actually will execute correctly uBut Oracle will do very strange things too when you attempt to update views in strange ways uThe standard mechanism for updating relatively complex views when it makes sense uses INSTEAD triggers

© 2014 Zvi M. Kedem 59 Using A Trigger To Update A View uCREATE TABLE r ( a CHAR (10) NOT NULL, b CHAR (10) NOT NULL, PRIMARY KEY (a) ); uCREATE TABLE s ( a CHAR (10) NOT NULL, c CHAR (10) NOT NULL, PRIMARY KEY (a) ); uCREATE VIEW t AS SELECT r.a AS a, r.b AS b, s.c AS c FROM r, s WHERE r.a = s.a;

© 2014 Zvi M. Kedem 60 Using A Trigger To Update A View uCREATE TRIGGER trigger02 INSTEAD OF UPDATE ON t REFERENCING NEW AS new BEGIN UPDATE s SET c = :new.c WHERE a = :old.a; END trigger02;. RUN; uUPDATE t SET c = 'q' WHERE a = '2';

© 2014 Zvi M. Kedem 61 Using A Trigger To Update A View uTables R, S, and view T before update on the view A B e 2 f A C m 2 n 3 o A B C e m 2 f n

© 2014 Zvi M. Kedem 62 Using A Trigger To Update A View uTables R, S, and view T after update on the view using trigger02 A B e 2 f A C m 2 q 3 o A B C e m 2 f q

© 2014 Zvi M. Kedem 63 Using A Trigger To Update (?) A View uTriggers will allow you to do very strange things

© 2014 Zvi M. Kedem 64 Using A Trigger To Update (?) A View uCREATE TRIGGER trigger03 INSTEAD OF UPDATE ON t REFERENCING NEW AS new BEGIN UPDATE r SET b = :new.c WHERE a = :old.a; END trigger03;. RUN uUPDATE t SET c = 'q' WHERE a = '2';

© 2014 Zvi M. Kedem 65 Using A Trigger To Update (?) A View uTables R, S, and view T before update on the view A B e 2 f A C m 2 n 3 o A B C e m 2 f n

© 2014 Zvi M. Kedem 66 Using A Trigger To Update (?) A View uTables R, S, and view T after update on the view using trigger03 A B e 2 q A C m 2 n 3 o A B C e m 2 q n

© 2014 Zvi M. Kedem 67 ALTER, DROP, REPLACE uIn general, if an object is CREATEd, in can subsequently be  ALTERed (some features are changed)  DROPped (removed) uSometimes it can be  REPLACEd (by a new object) uThis is why it is generally a good idea to name constraints, assertions, triggers, etc, while creating them

© 2014 Zvi M. Kedem 68 Privileges uPrivileges can be granted to user or PUBLIC for  Operations  References on  Base tables  Views uThese are technically part of Data Control Language or DCL

© 2014 Zvi M. Kedem 69 Types of Privileges uSelect uInsert uUpdate uDelete uReferences

© 2014 Zvi M. Kedem 70 Examples of Privileges uA typical instruction is:  GRANT SELECT, INSERT ON Customer TO Li, Brown; uPrivileges can be restricted to columns:  GRANT SELECT ON Customer.City TO Li, Brown; uIt is possible to grant all privileges by:  GRANT ALL ON Customer TO Li, Brown;

© 2014 Zvi M. Kedem 71 Passing Privileges uIt is possible to allow the users to pass the privileges to other users by issuing:  GRANT SELECT, INSERT ON Customer TO Li, Brown WITH GRANT OPTION; uThen Li can issue  GRANT SELECT ON Customer.City TO JONES;

© 2014 Zvi M. Kedem 72 Privilege To Reference uIt is possible to allow a user to use columns in a table as foreign keys referring to primary keys in a table to which the user has no privileges:  GRANT ALL ON Invoice TO Li;  GRANT REFERENCES (C) ON Customer TO Li; uThis privilege must be explicitly granted because Li may be able to check if a particular C appears in Customer  To check if C = 1 appears in Customer, Li attempts to INSERT an Invoice from C = 1  If C = 1 does not appear in Customer, the database will complain about violation of FOREIGN KEY constraint  If C = 1 appears in Customer, the database will not complain about violation of FOREIGN KEY constraint  This is how Li can check this and that’s why it is explicitly permitted

© 2014 Zvi M. Kedem 73 Privileges On Views uIt is possible to grant privileges on views.  Of course, the privilege must be meaningful. That is a privilege to update can be given only on a view that can be updated, etc.

© 2014 Zvi M. Kedem 74 Revoking Privileges uPrivileges can be revoked uThere are various way to specify what happens with privileges granted by somebody from whom a privilege is taken away

© 2014 Zvi M. Kedem 75 Key Ideas uCREATE for defining tables  Specifying domains  PRIMARY KEY  UNIQUE  FOREIGN KEY  NOT NULL  CHECK  DEFAULT uUNKNOWNs uMaintenance of referential integrity uConstraint checking  NOT DEFERRABLE  DEFERRABLE uASSERTIONs

© 2014 Zvi M. Kedem 76 Key Ideas uTrigger “on” INSERT, UPDATE, DELETE, “firing” BEFORE, AFTER, INSTEAD uViews uUpdating views with SQL UPDATE uUpdating views with INSTEAD TRIGGERs uALTER, DROP, REPLACE uPrivileges:  Select  Insert  Update  Delete  References