4 Schema Definition with SQL / DDL (II)
Total Page:16
File Type:pdf, Size:1020Kb
4.3 SQL/DDL - Constraints Different kinds of integrity constraints 4 Schema Definition with SQL / DDL (II) Important • on attributes, column constraints “ 0 <= accountValue“, “must not be NULL” 4.3 SQL/DDL – Constraints • cardinalities 4.3.1 Attribute and simple table constraints 4.3.2 Enforcing cardinality constraints and foreign keys • “semantic” constraints ("business rules") 4.3.3 Deferred constraints e.g. "The percentage of movies not older than one year must be 25% or more" 4.3.4 Assertions and triggers " After 100 loans a video tape (not DVD) has to be discarded" 4.3.5 Case study – Column constraint 4.3.6 Metadata management Specify constraint as part of column definition 4.3.7 Modifying and deleting definitions and more… – Table constraint More than one row involved, specify constraint after the column definitions HS / DBS04-06-DDL -2 2 Constraints 4.3.1 Attribute and simple table constraints Constraints may be violated when DB is changed • PRIMARY KEY (update, insert, delete) – Only once per table ð Exception – Not necessary, but omission is bad style ORA-02291: integrity constraint (SYS_C0067174) – May be column constraint (single attribute) or table violated - parent key not found constraint CREATE TABLE Tape( Constraint name (optional) t_id INTEGER PRIMARY KEY, m_id INTEGER NOT NULL, CONSTRAINT <name> <def> format CHAR(5), Advantage: error message shows violated constraint in a aquired DATE ) readable way CREATE TABLE People( ORA-02291: integrity constraint name VARCHAR(20), (FKMovieOnTape.SYS_C0067174) violated - parent birth_date DATE, ..., key not found CONSTRAINT pk PRIMARY KEY (name, birth_date) HS / DBS04-06-DDL -2 3 ) HS / DBS04-06-DDL -2 4 Not Null constraint Unique semantics • NOT NULL Strange UNIQUE semantics: Simplest constraint on attribute values, a column with more than one NULL value does column constraint not violate the UNIQUE constraint CREATE TABLE uniqueTest ( CREATE TABLE ExtraCharge ( x INTEGER UNIQUE, Simple example format CHAR(5) NOT NULL, y VARCHAR(2) extraCh DECIMAL(3,2)) ); Therefore UNIQUE INSERT INTO uniqueTest without NOT NULL VALUES (NULL,'a'); does not really make sense. • Default values SQL/DML INSERT INTO uniqueTest <attributeName> <attributeType> DEFAULT <value> statements, VALUES ( NULL,'a'); will be • UNIQUE discussed SELECT * FROM uniqueTest; later • Column contains only unique values X Y ---------- -- • Left over from SQL-89 (no primary key constraint) 1 a • Should be used for candidate keys a UNIQUE + NOT NULL =PRIMARY KEY • Column constraint or table constraint a HS / DBS04-06-DDL -2 5 HS / DBS04-06-DDL -2 6 1 CHECK clause Use of table constraints Predicates which must hold for each row General constraint syntax Enumeration: for column (except NOT NULL) and table constraints CHECK (VALUES IN (' comedy', 'entertainment', CREATE TABLE <tab> (< listOfColumnSpecs> 'suspense', 'drama', 'action', 'sci-fi')).. [[CONSTRAINT <constraintName>] Interval restriction: <constraint on columns or table>]0..n CHECK (extraCh >= 0), ) CHECK (extraCh < 10) equivalent to Constraint may be UNIQUE / PRIMARY KEY or CHECK clause CHECK (extraCh >= 0 AND extraCh < 10) or REFERENCES CREATE TABLE Customer( Multicolumn constraint: ... CREATE TABLE Accounts ( name VARCHAR(40), ... amount DECIMAL(9,2), zipcode VARCHAR(6), credit DECIMAL(7,2),..., ... , CONSTRAINT accountIsPos CONSTRAINT customerUniqueness CHECK amount + credit > 0 ) UNIQUE (name, zipcode, street, no) HS / DBS04-06-DDL -2 7 HS / DBS04-06-DDL -2 8 ) 4.3.2 Enforcing cardinality constraints Foreign keys • Constraint NOT ( m_ID IS NULL ) “Hard code" cardinality constraints in the database schema always true in example above for every row (1,1) (1,*) Movie Tape but the value of may not be among the isCopyOf ... m_Id mId values in table Movie Tape(id, acqDate,format, m_Id ) • m_ID is a foreign key in Tape table Movie(m_id, title, category, price_day, – Should exist, otherwise "missing entity" ~"dangling pointer" director, year) – "Find title of movie on tape with id=1175" would fail (1,..) ð NOT NULL constraint sufficient ? CREATE TABLE Tape ( CREATE TABLE Tape ( ..., t_id INTEGER PRIMARY KEY, movieId INTEGER NOT NULL, aquired DATE, CONSTRAINT movieExists Sufficient to enforce format CHAR(5) NOT NULL, FOREIGN KEY (movieID) REFERENCES Movie(mId) constraint only if mId INTEGER NOT NULL) foreign key ); HS / DBS04-06-DDL -2 9 HS / DBS04-06-DDL -2 10 Foreign keys Preserving referential integrity Let R be a relation with key k Important concept Referential integrity means: important fk Ì S(S) of relation S is foreign key if for all tuples sÎS Foreign key constraint holds holds: 1. The attributes of s.fk contain only NULL values or DBS has to prevent violations only values ¹ NULL – prevent execution of SQL statements which violate 2. If all attibutes of s.fk have value != NULL referential Integrity there exists a tuple rÎR and the value of s.fk is – INSERT, UPDATE, DELETE statements modify state the key of s – Update and Delete of a table may cause a violation – Violations cause an exception Tape Movie – Avoid violations by appropriate actions specified in a id format movie_id id title REFERENCES clause of the referencing table 0001 DVD 095 095 Psycho 0004 DVD 345 345 Star Wars I 0005 VHS 345 ... ... 0009 VHS 345 .... .... .... HS / DBS04-06-DDL -2 11 HS / DBS04-06-DDL -2 12 2 Preserving referential integrity Example: Referential Integrity in SQL/DDL • Actions on referenced tables: CREATE TABLE Tape( t_id INTEGER PRIMARY KEY, NOT NULL and ON DELETE CASCADE FOREIGN KEY format VARCHAR(5) NOT NULL, – delete all referenced tuples together guarantee e.g. if a movie is deleted, all tapes with this movie m_id INTEGER NOT NULL, constraint min=1 are deleted from the database CONSTRAINT tapeNotEmpty ON DELETE SET NULL FOREIGN KEY (m_id) REFERENCES Movie(m_id) ON DELETE CASCADE, ON DELETE DEFAULT CONSTRAINT formatCheck ON UPDATE CASCADE FOREIGN KEY (format) REFERENCES Format(name) – update key in referencing table ON DELETE SET DEFAULT); e.g. movie gets a new key, update value used as ON condition preserves constraint foreign key in the same way Format Tape Movie ON UPDATE SET NULL format extraCH id format movie_id id title DVD 1.00 0001 DVD 095 095 Psycho ON UPDATE SET DEFAULT VHS 0.00 0004 DVD 345 345 Star Wars I .... .... 0005 VHS 345 ... ... 0009 VHS 345 HS / DBS04-06-DDL -2 13 .... .... .... HS / DBS04-06-DDL -2 14 Example (cont.) SQL / DDL: Integrity constraints • Cardinality constraints (1,*) (1,1) Tape Movie id format movie_id id title Tape hold Movie 0001 DVD 095 095 Psycho 0004 DVD 345 345 Star Wars I 0005 VHS 345 ... ... 0009 VHS 345 .... .... .... – NOT NULL ensures min = 1 Delete from Movie CREATE TABLE Tape( Where id = 345; id INTEGER PRIMARY KEY, format CHAR(10) NOT NULL, Tape Movie m_id INTEGER NOT NULL, id format movie_id id title 0001 DVD 095 095 Psycho CONSTRAINT tapeNotEmpty .... .... .... ... ... FOREIGN KEY (m_id) REFERENCES Movie(m_id), CONSTRAINT formatCheck HS / DBS04-06-DDL -2 15 FOREIGN KEY (format) REFERENCES Format(name));HS / DBS04-06-DDL -2 16 Cardinality constraints Circular relationships born_in Example (1,*) (1,1) (0,1) (1,1) City is_mayor Person City Person id: INTEGER id: INTEGER (1,1) (0,1) is_mayor – NOT NULL ensures min = 1 • Table must be created in order to be referenced – UNIQUE ensures max= 1 • How to define “circular” constraints? – Specify constraints after table definition CREATE TABLE City( ALTER TABLE Person id INTEGER PRIMARY KEY, ADD CONSTRAINT birthPlaceReference mayor INTEGER UNIQUE NOT NULL, FOREIGN KEY (birthplace) CONSTRAINT mayorFK REFERENCES city(id); FOREIGN KEY (mayor) REFERENCES Person(id)); ALTER TABLE Person MODIFY COLUMN( birthplace NOT NULL); HS / DBS04-06-DDL -2 17 HS / DBS04-06-DDL -2 18 3 4.3.3 Deferred constraints Deferred constraints The Chicken-Egg problem Insertion violates foreign key constraint CREATE TABLE chicken(cID INT PRIMARY KEY, INSERT INTO chicken VALUES(1, 2); eID INT); CREATE TABLE egg(eID INT PRIMARY KEY, ORA-02291: integrity constraint cID INT); (chickenREFegg.SYS_C0067174) violated - parent key not found -- Example by J. Widom et al. INSERT INTO egg VALUES(2, 1); ALTER TABLE chicken ORA-02291: integrity constraint ADD CONSTRAINT chickenREFegg (eggREFchicken.SYS_C0067174) violated - parent FOREIGN KEY (eID) REFERENCES egg(eID); key not found ALTER TABLE egg Defer constraint checking ADD CONSTRAINT eggREFchicken ALTER TABLE chicken FOREIGN KEY (cID) REFERENCES chicken(cID) ; ADD CONSTRAINT chickenREFegg FOREIGN KEY (eID) REFERENCES egg(eID) What happens if an egg / chicken is inserted? INITIALLY DEFERRED DEFERRABLE; HS / DBS04-06-DDL -2 19 HS / DBS04-06-DDL -2 20 Deferred constraints and transactions Complex CHECK clauses Deferred constraints checked at the end of a transaction CHECK clause may be an arbitrary predicate Transaction: unit of work consisting of one or more operations on the DB over the DB (SQL 99) "COMMIT" closes a transaction CREATE TABLE competitors_Price(title:..., price...) INSERT INTO chicken VALUES(1, 2); CREATE TABLE movie (... -- constraint not checked here CONSTRAINT price_Limit INSERT INTO egg VALUES(2, 1); CHECK (“ At least 4 * lowest price”)) COMMIT; -- but here Variants INITIALLY DEFERRED DEFERRABLE Will be specified as SQL SELECT clause INITIALLY IMMEDIATE DEFERRABLE CHECK clause defined as a predicate over SET CONSTRAINT <name> [DEFERED|IMMEDIATE] one table only in most DBS implementations allow checking at arbitrary times HS / DBS04-06-DDL -2 21 HS / DBS04-06-DDL -2 22 4.3.4 Assertions and triggers Assertions and triggers SQL / DDL • Assertions