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
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
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
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
4.3.4 Assertions and triggers Assertions and triggers SQL / DDL • Assertions • Trigger – Integrity constraints defined independently from table (
4 TRIGGER Triggering applications • Example for action on DB • Triggers very useful for triggering Insert into Order_Line_Items …(4711,50) actions outside DB
Triggered update Order_Line_Items(itemNo,qty, orderNo) – Triggering audit trails If table is changed store an entry about this event in a special place (the audit trail) Inventory (partNO, stock,reserved..)
– Triggering an application program If a customer has rented a tape and she has CREATE TRIGGER my_Trigger …UPDATE..ON Order_Line_items trigger event a non-NULL email address, send her a mail UPDATE inventory SET reserved = reserved + qty trigger action WHERE partNo = itemNo HS / DBS04-06-DDL -2 25 HS / DBS04-06-DDL -2 26
4.3.5 Case study Example CREATE TABLE Customer ( • Relation Schema Video-DB mem_no INTEGER PRIMARY KEY, name VARCHAR) NOT NULL, first_name VARCHAR(30), zip CHAR (10), CREATE TABLE Movie( city VARCHAR(30), m_id INTEGER PRIMARY KEY, ); title VARCHAR(60) NOT NULL, cat CHAR(20), year DATE, director VARCHAR(40), CREATE TABLE Phones ( price_Day DECIMAL(4,2), phone VARCHAR(40), length INTEGER, customer INTEGER, CONSTRAINT plausible_year CONSTRAINT pk_phone CHECK (year > TO_DATE('01.01.1900','DD.MM.YYYY')), PRIMARY KEY(phone,customer), CONSTRAINT allowedPrice CONSTRAINT fk_phone CHECK ( (price_Day >= 0) AND (price_Day < 10.0)) FOREIGN KEY (customer) ); REFERENCES Customer ( mem_no ) ON DELETE CASCADE ); HS / DBS04-06-DDL -2 27
Example CREATE TABLE Tape( t_id INTEGER PRIMARY KEY, CREATE TABLE Format ( m_id INTEGER NOT NULL, format CHAR(5)PRIMARY KEY, format CHAR(5), extraCh DECIMAL (3,2) aquired DATE, ); CONSTRAINT movieExists FOREIGN KEY ( m_id) REFERENCES movie(m_id ) CREATE TABLE Rental ( ON DELETE CASCADE ); tape_id INTEGER NOT NULL, mem_no INTEGER, from_date DATE NOT NULL, until_date DATE, ALTER TABLE Tape PRIMARY KEY (tape_id, from_date), ADD ( CONSTRAINT formatExists CONSTRAINT fk_Tape FOREIGN KEY (format) REFERENCES Format(format) FOREIGN KEY (tape_id) REFERENCES Tape(t_id ) ON DELETE SET NULL); ON DELETE CASCADE, CONSTRAINT fk_Customer FOREIGN KEY (mem_no) REFERENCES Customer ( mem_no ) ON DELETE CASCADE); HS / DBS04-06-DDL -2 30
5 Note on Relational Database Design CREATE TABLE Actor ( stage_name VARCHAR(30) PRIMARY KEY, Direct design of Relational DB real_name VARCHAR(30), Referenced column – some design tools do not support ER-M but birth_date DATE must be unique ); use RDM directly – Relationships defined by foreign keys CREATE TABLE Starring ( movie_id INTEGER, – Reengineering tools produce RDB schema with actor_name VARCHAR(30), foreign keys CONSTRAINT pkStarr PRIMARY KEY ( movie_id, actor_name), CONSTRAINT foreignKeyMovieID FOREIGN KEY ( movie_id) ACTOR Starring Movie REFERENCES Movie (m_id) ON DELETE CASCADE, name name m_id CONSTRAINT foreignKeyStagename … movie_id title… FOREIGN KEY ( actor_name) … REFERENCES Actor(stage_name) ON DELETE CASCADE
); HS / DBS04-06-DDL -2 32
MovieDB reengineered 4.3.6 Metadata management
ACTOR PK STAGE_NAME Meta data MOVIE REAL_NAME BIRTH_DATE PK M_ID – All definitions and other "data on data" are called
TITLE CAT metadata FORMAT YEAR DIRECTOR PK FORMAT STARRING PRICE_DAY – Stored in system data structures LENGTH EXTRACH PK,FK1 MOVIE_ID PK,FK2 ACTOR_NAME – Data structures for metadata called
CUSTOMER "the catalogue“ or “data dictionary” PK MEM_NO TAPE in particular when used for more than one DB NAME PK T_ID FIRST_NAME ZIP FK2 M_ID CITY FK1 FORMAT – In most systems stored as tables EMAIL AQUIRED – Makes metadata "first class": (using Visio) may be queried und modified in the same way as PHONES RENTAL PK PHONE PK,FK2 TAPE_ID the data tables PK,FK1 CUSTOMER PK FROM_DATE
FK1 MEM_NO UNTIL_DATE Select
HS / DBS04-06-DDL -2 33 HS / DBS04-06-DDL -2 34
Metadata management: example Virtual tables: views
Querying the catalog using SQL: More SQL Schema Definition Statements Attributes of the a first example (ORACLE) user_constraints – CREATE TABLE defines base tables table – View: virtual table, has a definition, but no extent, SQL> SELECT constraint_name,search_condition, definition is executed when table is accessed delete_rule FROM user_constraints CREATE VIEW
ALLOWEDPRICEALLOWEDPRICE pricePDaypricePDay >=>= 0)0) ANDAND ((pricePDaypricePDay << 100.0)100.0) To be discussed later… SYS_C001363SYS_C001363 TAPE_MOVIETAPE_MOVIE CASCADCASCADEE No standard for metadata management! completely different in Postgres! HS / DBS04-06-DDL -2 35 HS / DBS04-06-DDL -2 36
6 4.3.7 Modifying and deleting definitions Deletion of schema elements
ALTER TABLE Table delete ALTER TABLE
Many more variants of ALTER statement see manual
HS / DBS04-06-DDL -2 37 HS / DBS04-06-DDL -2 38
Sequences Oracle and more Sequences of numbers…. • Oracle – useful for artificial keys: 1,2,3,….4711,… – PRIMARY KEY, NOT NULL, UNIQUE, FOREIGN – Where is the problem or KEY, REFERENCES, CHECK supported, uses How to count consistently? sequence objects – Persistence required! • Postgres – very similar to ORACLE (SQL99), SERIAL type as • Pseudo columns an abbreviation of sequence objects Create SEQUENCE tapeSeq; -- different • MySQL (V3.x) -- options – PRIMARY KEY, NOT NULL, UNIQUE supported INSERT INTO Tape – FOREIGN KEY, REFERENCES, CHECK accepted (t_Id,m_Id,format,aquired) (for compatibility) but not supported VALUES – Simple but risky creation of unique artificial key (tapeSeq.nextval,4711,'DVD','2003-4-4'); values:
HS / DBS04-06-DDL -2 39 [
Summary
• Standard Query Language (SQL) – Data definition language (DDL) – Data manipulation language (DML) – In almost all current DBMS – All SQL implementations differ from standard – core SQL99 is basically supported by high-end DBS
• Important terms and concepts – Data types – Create, change, delete tables – Referential integrity – Integrity constraints – TRIGGERS
HS / DBS04-06-DDL -2 41
7