Integrity Constraints

Slides:



Advertisements
Similar presentations
primary key constraint foreign key constraint
Advertisements

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 16 Relational Database Design Algorithms and Further Dependencies.
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.
Temple University – CIS Dept. CIS616– Principles of Data Management V. Megalooikonomou Functional Dependencies (based on notes by Silberchatz,Korth, and.
Carnegie Mellon Carnegie Mellon Univ. Dept. of Computer Science Database Applications C. Faloutsos Integrity Constraints.
Database Management COP4540, SCS, FIU Functional Dependencies (Chapter 14)
SQL Lecture 10 Inst: Haya Sammaneh. Example Instance of Students Relation  Cardinality = 3, degree = 5, all rows distinct.
CMU SCS Carnegie Mellon Univ. Dept. of Computer Science /615 - DB Applications Lecture #16: Schema Refinement & Normalization - Functional Dependencies.
The Relational Model Class 2 Book Chapter 3 Relational Data Model Relational Query Language (DDL + DML) Integrity Constraints (IC) (From ER to Relational)
Cs3431 Constraints Sections 6.1 – 6.5. cs3431 Example CREATE TABLE Student ( sNum int, sName varchar (20), prof int, CONSTRAINT pk PRIMARY KEY (snum),
CMSC424: Database Design Instructor: Amol Deshpande
CMSC424: Database Design Instructor: Amol Deshpande
Chapter 7: Relational Database Design. ©Silberschatz, Korth and Sudarshan7.2Database System Concepts Chapter 7: Relational Database Design First Normal.
SPRING 2004CENG 3521 The Relational Model Chapter 3.
1 Relational Model. 2 Relational Database: Definitions  Relational database: a set of relations  Relation: made up of 2 parts: – Instance : a table,
The Relational Model Lecture 3 Book Chapter 3 Relational Data Model Relational Query Language (DDL + DML) Integrity Constraints (IC) From ER to Relational.
1 CMSC424, Spring 2005 CMSC424: Database Design Lecture 9.
1 Functional Dependency and Normalization Informal design guidelines for relation schemas. Functional dependencies. Normal forms. Normalization.
1 Schema Refinement and Normal Forms Chapter 19 Raghu Ramakrishnan and J. Gehrke (second text book) In Course Pick-up box tomorrow.
1 CMSC424, Spring 2005 CMSC424: Database Design Lecture 8.
CMSC424: Database Design Instructor: Amol Deshpande
CMSC424: Database Design Instructor: Amol Deshpande
CMPT 354, Simon Fraser University, Fall 2008, Martin Ester 157 Database Systems I SQL Constraints and Triggers.
Chapter 8: Relational Database Design First Normal Form First Normal Form Functional Dependencies Functional Dependencies Decomposition Decomposition Boyce-Codd.
©Silberschatz, Korth and Sudarshan7.1Database System Concepts Chapter 7: Relational Database Design First Normal Form Pitfalls in Relational Database Design.
Review Three things managed by a DBMS 1.Data organization  E/R Model  Relational Model 2.Data Retrieval  Relational Algebra  SQL 3.Data Integrity.
Department of Computer Science and Engineering, HKUST Slide 1 Comp 231 Database Management Systems Comp 231 Database Management Systems 6. Integrity Constraints.
Chapter 10 Functional Dependencies and Normalization for Relational Databases.
The Relational Model These slides are based on the slides of your text book.
FUNCTIONAL DEPENDENCIES. Chapter Outline 1 Informal Design Guidelines for Relational Databases 1.1Semantics of the Relation Attributes 1.2 Redundant Information.
Functional Dependencies An example: loan-info= Observe: tuples with the same value for lno will always have the same value for amt We write: lno  amt.
SCUJ. Holliday - coen 1784–1 Schedule Today: u Normal Forms. u Section 3.6. Next u Relational Algebra. Read chapter 5 to page 199 After that u SQL Queries.
BCNF & Lossless Decomposition Prof. Sin-Min Lee Department of Computer Science.
1 The Relational Model. 2 Why Study the Relational Model? v Most widely used model. – Vendors: IBM, Informix, Microsoft, Oracle, Sybase, etc. v “Legacy.
FALL 2004CENG 351 File Structures and Data Management1 Relational Model Chapter 3.
1.1 CAS CS 460/660 Relational Model. 1.2 Review E/R Model: Entities, relationships, attributes Cardinalities: 1:1, 1:n, m:1, m:n Keys: superkeys, candidate.
Ihr Logo Fundamentals of Database Systems Fourth Edition El Masri & Navathe Chapter 10 Functional Dependencies and Normalization for Relational Databases.
Ihr Logo Fundamentals of Database Systems Fourth Edition El Masri & Navathe Chapter 10 Functional Dependencies and Normalization for Relational Databases.
FEN Introduction to the database field:  The Relational Model Seminar: Introduction to relational databases.
Logical Database Design (1 of 3) John Ortiz Lecture 6Logical Database Design (1)2 Introduction  The logical design is a process of refining DB schema.
1 Lecture 6: Schema refinement: Functional dependencies
CMU SCS Carnegie Mellon Univ. Dept. of Computer Science /615 - DB Applications C. Faloutsos – A. Pavlo Lecture#16: Schema Refinement & Normalization.
1 Dept. of CIS, Temple Univ. CIS616/661 – Principles of Data Management V. Megalooikonomou Integrity Constraints (based on slides by C. Faloutsos at CMU)
CSC 411/511: DBMS Design Dr. Nan Wang 1 Schema Refinement and Normal Forms Chapter 19.
Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide
Constraints and Triggers. What’s IC? Integrity Constraints define the valid states of SQL-data by constraining the values in the base tables. –Restrictions.
Minimum Cover of F. Minimal Cover for a Set of FDs Minimal cover G for a set of FDs F: –Closure of F = closure of G. –Right hand side of each FD in G.
CMU SCS Carnegie Mellon Univ. Dept. of Computer Science /615 - DB Applications Lecture #16: Schema Refinement & Normalization - Functional Dependencies.
Chapter 5 : Integrity And Security  Domain Constraints  Referential Integrity  Security  Triggers  Authorization  Authorization in SQL  Views 
ICS 421 Spring 2010 Relational Model & Normal Forms Asst. Prof. Lipyeow Lim Information & Computer Science Department University of Hawaii at Manoa 1/19/20101Lipyeow.
CS34311 The Relational Model. cs34312 Why Relational Model? Currently the most widely used Vendors: Oracle, Microsoft, IBM Older models still used IBM’s.
MIS 3053 Database Design And Applications The University Of Tulsa Professor: Akhilesh Bajaj Normal Forms Lecture 1 © Akhilesh Bajaj, 2000, 2002, 2003.
IST Database Normalization Todd Bacastow IST 210.
Chapter 8 Relational Database Design. 2 Relational Database Design: Goals n Reduce data redundancy (undesirable replication of data values) n Minimize.
11/06/97J-1 Principles of Relational Design Chapter 12.
Normalization and FUNctional Dependencies. Redundancy: root of several problems with relational schemas: –redundant storage, insert/delete/update anomalies.
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.
©Silberschatz, Korth and Sudarshan6.1Database System Concepts Chapter 6: Integrity Constraints Domain Constraints Referential Integrity Assertions Triggers.
CENG 351 File Structures and Data Management1 Relational Model Chapter 3.
CSC 411/511: DBMS Design Dr. Nan Wang 1 Schema Refinement and Normal Forms Chapter 19.
Chapter 6: Integrity (and Security)
Constraints and Triggers
Integrity Constraints
אילוצי שלמות אילוצי תחום מפתחות ומפתחות זרים טריגרים triggers
The Relational Model Relational Data Model
Temple University – CIS Dept. CIS331– Principles of Database Systems
CSC 453 Database Systems Lecture
Presentation transcript:

Integrity Constraints

Review Three things managed by a DBMS Data organization Data Retrieval E/R Model Relational Model Data Retrieval Relational Algebra Relational Calculus SQL Data Integrity and Database Design Integrity Constraints Functional Dependencies Normalization

Integrity Constraints Purpose: prevent semantic inconsistencies in data e.g.: e.g.: 4 kinds of IC’s: 1. Key Constraints 2. Attribute Constraints 3. Referential Integrity Constraints 4. Global Constraints No entry for Kenmore... ???

IC’s What are they? predicates on the database must always be true (:, checked whenever db gets updated) There are the following 4 types of IC’s: Key constraints (1 table) e.g., 2 accts can’t share the same acct_no Attribute constraints (1 table) e.g., 2 accts must have nonnegative balance Referential Integrity constraints ( 2 tables) E.g. bnames associated w/ loans must be names of real branches

Key Constraints Idea: specifies that a relation is a set, not a bag SQL examples: 1. Primary Key: CREATE TABLE branch( bname CHAR(15) PRIMARY KEY, bcity CHAR(20), assets INT); or CREATE TABLE depositor( cname CHAR(15), acct_no CHAR(5), PRIMARY KEY(cname, acct_no)); 2. Candidate Keys: CREATE TABLE customer ( ssn CHAR(9) PRIMARY KEY, cname CHAR(15), address CHAR(30), city CHAR(10), UNIQUE (cname, address, city);

Key Constraints Effect of SQL Key declarations PRIMARY (A1, A2, .., An) or UNIQUE (A1, A2, ..., An) Insertions: check if any tuple has same values for A1, A2, .., An as any inserted tuple. If found, reject insertion Updates to any of A1, A2, ..., An: treat as insertion of entire tuple Primary vs Unique (candidate) 1 primary key per table, several unique keys allowed. Only primary key can be referenced by “foreign key” (ref integrity) DBMS may treat primary key differently (e.g.: implicitly create an index on PK) 4. NULL values permitted in UNIQUE keys but not in PRIMARY KEY

Attribute Constraints Idea: Attach constraints to values of attributes Enhances types system (e.g.: >= 0 rather than integer) In SQL: 1. NOT NULL e.g.: CREATE TABLE branch( bname CHAR(15) NOT NULL, .... ) Note: declaring bname as primary key also prevents null values 2. CHECK e.g.: CREATE TABLE depositor( balance int NOT NULL, CHECK( balance >= 0), affect insertions, update in affected columns

CHECK constraint in Oracle CHECK cond where cond is: Boolean expression evaluated using the values in the row being inserted or updated, and Does not contain subqueries; sequences; the SQL functions SYSDATE, UID, USER, or USERENV; or the pseudocolumns LEVEL or ROWNUM Multiple CHECK constraints No limit on the number of CHECK constraints you can define on a column CREATE TABLE credit_card( .... balance int NOT NULL, CHECK( balance >= 0), CHECK (balance < limit), )

Referential Integrity Constraints Idea: prevent “dangling tuples” (e.g.: a loan with a bname of ‘Kenmore’ when no Kenmore tuple is not in branch table) Referencing Relation (e.g. loan) Referenced Relation (e.g. branch) “foreign key” bname primary key bname Ref Integrity: ensure that: foreign key value  primary key value (note: need not to ensure , i.e., not all branches have to have loans)

Referential Integrity Constraints bname bname x Referencing Relation (e.g. loan) parent Referenced Relation (e.g. branch) x x child In SQL: CREATE TABLE branch( bname CHAR(15) PRIMARY KEY ....) CREATE TABLE loan ( ......... FOREIGN KEY bname REFERENCES branch); Affects: 1) Insertions, updates of referencing relation 2) Deletions, updates of referenced relation

Referential Integrity Constraints x parent tj x x child what happens when we try to delete this tuple? A B Ans: Oracle allows the following possibilities No action RESTRICT: reject deletion/ update SET TO NULL: set ti [c], tj[c] = NULL SET TO DEFAULT: set ti [c], tj[c] = default_val CASCADE: propagate deletion/update DELETE: delete ti, tj UPDATE: set ti[c], tj[c] to updated values

Referential Integrity Constraints x tj x x what happens when we try to delete this tuple? Emp Dept ALTER TABLE Dept ADD Primary Key (deptno); ALTER TABLE Emp ADD FOREIGN KEY (Deptno) REFERENCES Dept(Deptno) [ACTION]; Action: 1) ON DELETE NO ACTION left blank (deletion/update rejected) 2) ON DELETE SET NULL/ ON UPDATE SET NULL sets ti[c] = NULL, tj[c] = NULL 3) ON DELETE CASCADE deletes ti, tj ON UPDATE CASCADE sets ti[c], tj[c] to new key values

Global Constraints Idea: two kinds 1) single relation (constraints spans multiple columns) E.g.: CHECK (total = svngs + check) declared in the CREATE TABLE Example: All Bkln branches must have assets > 5M CREATE TABLE branch ( .......... bcity CHAR(15), assets INT, CHECK (NOT(bcity = ‘Bkln’) OR assets > 5M)) Affects: insertions into branch updates of bcity or assets in branch 2) Multiple Relations: NOT supported in Oracle Need to be implemented as a Trigger

Global Constraints (NOT in Oracle) SQL example: 2) Multiple relations: every loan has a borrower with a savings account CHECK (NOT EXISTS ( SELECT * FROM loan AS L WHERE NOT EXISTS( FROM borrower B, depositor D, account A WHERE B.cname = D.cname AND D.acct_no = A.acct_no AND L.lno = B.lno))) Problem: Where to put this constraint? At depositor? Loan? .... Ans: None of the above: CREATE ASSERTION loan-constraint CHECK( ..... ) Checked with EVERY DB update! very expensive.....

Global Constraints Issues: 1) How does one decide what global constraint to impose? 2) How does one minimize the cost of checking the global constraints? Ans: Functional dependencies. but before we go there

Deferring the constraint checking SET ALL CONSTRAINTS DEFERRED; Defers all constraint checks till the end of the transaction Especially useful in enforcing Referential integrity Insert new rows into ‘Child’ table but referred key is not yet in Parent Insert corresponding row in ‘Parent’ table Constraint checking done at the end of the transaction Can also defer individual constraint checking by specifying the constraint name Finding the constraint information in Oracle SELECT * FROM USER_CONSTRAINTS; SELECT * FROM USER_CONS_COLS;

Summary: Integrity Constraints Constraint Type Where declared Affects... In Oracle ? Key Constraints CREATE TABLE (PRIMARY KEY, UNIQUE) Insertions, Updates Yes Attribute Constraints CREATE DOMAIN (Not NULL, CHECK) CREATE DOMAIN not supported in Oracle Referential Integrity Table Tag (FOREIGN KEY .... REFERENCES ....) 1.Insertions into referencing rel’n 2. Updates of referencing rel’n of relevant attrs 3. Deletions from referenced rel’n 4. Update of referenced rel’n Possible Actions: -- Update/delete no aciton -- delete CASCADE -- delete SET NULL, SET DEFAULT,… Global Consraints Table Tag (CHECK) or outside table (CREATE ASSERTION) 1. For single rel’n constraint, with insertion, deletion of relevant attrs 2. For assesrtions w/ every db modification Assertions, domains not supported in Oracle.

Review Three things managed by a DBMS Data organization Data Retrieval E/R Model Relational Model Data Retrieval Relational Algebra Relational Calculus SQL Data Integrity and Database Design Integrity Constraints Functional Dependencies Constraints that hold for legal instance of the database Example: Every customer should have a single credit card Normalization

Functional Dependencies A B  C “ AB determines C” two tuples with the same values for A and B will also have the same value for C Constraints that will hold on all “legal” instances of the database for the specific business application.  In most cases, specified by a database designer/business architect

Functional Dependencies Shorthand: C  BD same as C  B C  D Be careful! AB  C not the same as AC BC Not true

Functional Dependencies Example: suppose R = { A, B, C, D, E, H} and we determine that: F = { A  BC, B  CE, A  E, AC  H, D  B} Then we determine the ‘canonical cover’ of F: Fc = { A  BH, B  CE, D  B} ensuring that F and Fc are equivalent Note: F requires 5 assertions Fc requires 3 assertions Canonical cover (or minimal cover) algorithm: In the book (not covered here).

Functional Dependencies Equivalence of FD sets: FD sets F and G are equivalent if the imply the same set of FD’s e.g. A B and B  C : implies A  C equivalence usually expressed in terms of closures Closures: For any FD set, F, F+ is the set of all FD’s implied by F. can calculate in 2 ways: (1) Attribute Closure (2) Armstrong’s axioms Both techniques tedious-- will do only for toy examples F equivalent to G iff F+ = G+

Armstrong’s Axioms A. Fundamental Rules (W, X, Y, Z: sets of attributes) 1. Reflexivity If Y X then X  Y 2. Augmentation If X  Y then WX  WY 3. Transitivity If X Y and Y  Z then XZ B. Additional rules (can be proved from A) 4. UNION: If X  Y and X  Z then X  YZ 5. Decomposition: If X  YZ then X  Y, X Z 6. Pseudotransitivity: If X  Y and WY  Z then WX Z 2 3 Proving 4.(sketch): X Y => XXXY =>XXY XYYZ => X YZ For every step we used the rules from A.

FD Closures Using Armstrong’s Axioms Given; F = { A  BC, (1) B  CE, (2) A  E, (3) AC  H, (4) D  B} (5) Exhaustively apply Armstrong’s axioms to generate F+ F+ = F  1. { A  B, A  C}: decomposition on (1) 2. { A  CE}: transitivity to 1.1 and (2) 3. { B  C, B  E}: decomp to (2) 4. { A  C, A  E} decomp to 2 5. { A  H} pseudotransitivity to 1.2 and (4)

Attribute Closures Given; Attribute closure A R = { A, B, C, D, E, H,I} and: F = { A  BC, C D, CE, AH  I} Attribute closure A Iteration Result ----------------------------------- 0 A 1 A B C 2 A B C D 3 A B C D E What is the closure of A (A+) ? Algorithm att-closure (X: set of Attributes) Result  X repeat until stable for each FD in F, Y  Z, do if Y Result then Result  Result  Z Better to determine if a set of attributes is a key

Functional dependencies Our goal: given a set of FD set, F, find an alternative FD set, G that is: smaller equivalent Bad news: Testing F=G (F+ = G+) is computationally expensive Good news: Canonical Cover algorithm: given a set of FD, F, finds minimal FD set equivalent to F Minimal: can’t find another equivalent FD set w/ fewer FD’s

FD so far... 1. Canonical Cover algorithm result (Fc) guaranteed to be the minimal FD set equivalent to F 2. Closure Algorithms a. Armstrong’s Axioms: more common use: test for extraneous attributes in C.C. algorithm b. Attribute closure: more common use: test for superkeys 3. Purposes a. minimize the cost of global integrity constraints so far: min gic’s = |Fc| In fact.... Min gic’s = 0 (FD’s for “normalization”)

Another use of FD’s: Schema Design Example: R = R: “Universal relation” tuple meaning: Jones has a loan (L-17) for $1000 taken out at the Downtown branch in Bkln which has assets of $9M Design: + : fast queries (no need for joins!) - : redudancy: update anomalies examples? deletion anomalies