Chapter 4 Intermediate SQL: Integrity Constraints.

Slides:



Advertisements
Similar presentations
Relational Database. Relational database: a set of relations Relation: made up of 2 parts: − Schema : specifies the name of relations, plus name and type.
Advertisements

Database Management Systems, R. Ramakrishnan and J. Gehrke1 The Relational Model Chapter 3.
©Silberschatz, Korth and Sudarshan6.1Database System Concepts Chapter 6: Integrity (and Security) Domain Constraints Referential Integrity Assertions Triggers.
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),
CMPT 354, Simon Fraser University, Fall 2008, Martin Ester 28 Database Systems I The Relational Data Model.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 3 The Basic (Flat) Relational Model.
Introduction to Structured Query Language (SQL)
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 8.
Introduction to Structured Query Language (SQL)
Database Constraints. Database constraints are restrictions on the contents of the database or on database operations Database constraints provide a way.
Chapter 6: Integrity Objective Key Constraints (Chapter 2) Cardinality Constraints (Chapter 2) Domain Constraints Referential Integrity Assertions Triggers.
Chapter 6: Integrity and Security Thomas Nikl 19 October, 2004 CS157B.
©Silberschatz, Korth and Sudarshan6.1Database System Concepts Chapter 6: Integrity and Security Domain Constraints Referential Integrity Assertions Triggers.
The Relational Model These slides are based on the slides of your text book.
AL-MAAREFA COLLEGE FOR SCIENCE AND TECHNOLOGY INFO 232: DATABASE SYSTEMS CHAPTER 7 INTRODUCTION TO STRUCTURED QUERY LANGUAGE (SQL) Instructor Ms. Arwa.
SCUHolliday - coen 1789–1 Schedule Today: u Constraints, assertions, triggers u Read Sections , 7.4. Next u Triggers, PL/SQL, embedded SQL, JDBC.
1 The Relational Model Instructor: Mohamed Eltabakh
Lecture 7 Integrity & Veracity UFCE8K-15-M: Data Management.
10 Copyright © 2009, Oracle. All rights reserved. Using DDL Statements to Create and Manage Tables.
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.
Relational Data Model Ch. 7.1 – 7.3 John Ortiz Lecture 3Relational Data Model2 Why Study Relational Model?  Most widely used model.  Vendors: IBM,
7 1 Chapter 7 Introduction to Structured Query Language (SQL) Database Systems: Design, Implementation, and Management, Seventh Edition, Rob and Coronel.
Slide Chapter 5 The Relational Data Model and Relational Database Constraints.
6 1 Lecture 8: Introduction to Structured Query Language (SQL) J. S. Chou, P.E., Ph.D.
Chapter 4 Advanced SQL: Integrity Constraints. 2 n Ensure Data Consistency n Domain Constraints  enforce valid attribute values from domain sets  domain.
Chapter 8: SQL. Data Definition Modification of the Database Basic Query Structure Aggregate Functions.
Database Systems Design, Implementation, and Management Coronel | Morris 11e ©2015 Cengage Learning. All Rights Reserved. May not be scanned, copied or.
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.
Advanced SQL: Triggers & Assertions
Dec 8, 2003Murali Mani Constraints B term 2004: lecture 15.
1 SQL - II Data Constraints –Applying data constraints Types of data constraints –I/O constraints The PRIMARY KEY constraints The FOREIGN KEY constraints.
Chapter 9 Constraints. Chapter Objectives  Explain the purpose of constraints in a table  Distinguish among PRIMARY KEY, FOREIGN KEY, UNIQUE, CHECK,
Oracle 11g: SQL Chapter 4 Constraints.
Database Lab Lecture 1. Database Languages Data definition language ( DDL ) Data definition language –defines data types and the relationships among them.
7 1 Constraints & Triggers Chapter Constraints and triggers? Constraints: Certain properties that the DBMS is required to enforce –E.g. primary.
Chapter 4 Constraints Oracle 10g: SQL. Oracle 10g: SQL 2 Objectives Explain the purpose of constraints in a table Distinguish among PRIMARY KEY, FOREIGN.
Constraints and Triggers. What’s IC? Integrity Constraints define the valid states of SQL-data by constraining the values in the base tables. –Restrictions.
Managing Constraints. 2 home back first prev next last What Will I Learn? Four different functions that the ALTER statement can perform on constraints.
CSE314 Database Systems Lecture 3 The Relational Data Model and Relational Database Constraints Doç. Dr. Mehmet Göktürk src: Elmasri & Navanthe 6E Pearson.
ITEC 3220A Using and Designing Database Systems Instructor: Prof. Z. Yang Course Website: 3220a.htm
Constraints Lesson 8. Skills Matrix Constraints Domain Integrity: A domain refers to a column in a table. Domain integrity includes data types, rules,
Chapter 5 : Integrity And Security  Domain Constraints  Referential Integrity  Security  Triggers  Authorization  Authorization in SQL  Views 
Session 1 Module 1: Introduction to Data Integrity
©Silberschatz, Korth and Sudarshan1 Structured Query Language (SQL) Data Definition Language Domains Integrity Constraints.
CS34311 The Relational Model. cs34312 Why Relational Model? Currently the most widely used Vendors: Oracle, Microsoft, IBM Older models still used IBM’s.
Including Constraints. What Are Constraints? Constraints enforce rules at the table level. You can use constraints to do the following: – Enforce rules.
Lecture 03 Constraints. Example Schema CONSTRAINTS.
Database System Concepts, 6 th Ed. ©Silberschatz, Korth and Sudarshan See for conditions on re-usewww.db-book.com Chapter 4: Intermediate.
SCUHolliday - coen 1789–1 Schedule Today: u Constraints, assertions, triggers u Read Sections , 7.4. Next u Embedded SQL, JDBC. u Read Sections.
CSC314 DAY 8 Introduction to SQL 1. Chapter 6 © 2013 Pearson Education, Inc. Publishing as Prentice Hall SQL OVERVIEW  Structured Query Language  The.
Murali Mani Constraints. Murali Mani Keys: Primary keys and unique CREATE TABLE Student ( sNum int, sName varchar (20), dept char (2), CONSTRAINT key.
Constraints Advanced Database Systems Dr. AlaaEddin Almabhouh.
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.
©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.
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.
Data Integrity & Indexes / Session 1/ 1 of 37 Session 1 Module 1: Introduction to Data Integrity Module 2: Introduction to Indexes.
Database Constraints Ashima Wadhwa. Database Constraints Database constraints are restrictions on the contents of the database or on database operations.
Chapter 6: Integrity (and Security)
Constraints and Triggers
Instructor: Mohamed Eltabakh
The Relational Model Relational Data Model
SQL DATA CONSTRAINTS.
Presentation transcript:

Chapter 4 Intermediate SQL: Integrity Constraints

2 n Ensure Data Consistency n Domain Constraints  enforce valid attribute values from domain sets  domain set may exclude null values n Referential Integrity (especially Foreign-Key Integrity)  a constraint involving two relations  used for specifying a relationship among tuples in two relations, the referencing relation and the referenced relation  (foreign-Key Constraint) tuples in the referencing relation, r 2, have attributes FK (called foreign key) that reference the primary key PK of the referenced relation r 1  FK of r 2 is a foreign key of r 1 with primary key PK if  t 2  r 2,  t 1  r 1 such that t 1 [PK] = t 2 [FK]

3 Integrity Constraints n Updates on foreign keys: Let FK of r 2 be a foreign key that references the primary key PK of r 1. To enforce the referential integrity: n Insert: add t 2 to r 2. n Delete: remove t 1 from r 1.  Action 1. Deny the deletion request (an inappropriate option), or  Action 2. Delete all tuples t in r 2 such that t[FK] = t 1 [PK] n Modify:  Referencing relation - if t 2 [FK] in r 2 is modified to t 2 ’[FK], then  Referenced relation - if t 1 [PK] in r 1 is modified to t 1 ’[PK], – Referential integrity in SQL - indicate primary key/candidate key/foreign key during the creation of a table Then t 2 [FK]   PK (r 1 ); otherwise, reject If t 1 [PK]   FK (r 2 ), then it must be the case that t 2 ’[FK]   PK (r 1 ); otherwise, reject then use the deletion policy for modification on t 1 [PK]

4 Example. Create table customer Create table branch (customer-name char(20) not null, (branch-name char(15) not null, customer-street char(30), branch-city char(30), customer-city char(30), assets integer, primary key (customer-name)) primary key (branch-name), check (assets  0)) Create table account (account-number char(10) not null, branch-name char(15), balance integer, primary key (account-number), foreign key (branch-name) references branch, check (balance  0)) Create table depositor (customer-namechar(20) not null, account-numberchar(10) not null, primary key (customer-name, account-number), foreign key (customer-name) references customer, foreign key (account-number) references account)

5 Integrity Constraints

6 SQL: CREATE TABLE Statements n Basic syntax of the CREATE TABLE statement: CREATE TABLE ( ) table element ::= | table elementtable element list, column definition ::= | table constraint definition n The table definition (relational properties in Oracle) includes  data in the column definitions, and  rules for handling data in the table constraint definition n A table is more like an object (with its data and methods) than just a simple passive file.

7 Relational Properties (Oracle 8i) Column Definition Table Constraint Definition

8 SQL: Column Definitions in CREATE TABLE n Column definitions: column definition ::= default clause [ ] column constraint [ ] n Each column name must have a data type (e.g. numeric, char strings, bit), and optional default values and constraints. n Each column definition can be modified by using a ALTER TABLE statement. n The default clause specify the default value to be inserted into the column if an explicit value does not exist

9 SQL: Column Definitions in CREATE TABLE n Default Clause: default clausedefault option ::= DEFAULT default option ::= | | NULL n A literal value is a string of alphabetic or numeric characters. n A system value can be current timestamp/date/current user ID. n Example. CREATE TABLE Account (Acc_num INTEGER DEFAULT 1, Acc_type CHAR(1) DEFAULT 'A', Acc_descr CHAR(20) DEFAULT 'New Account');

10 Column Definitions in CREATE TABLE: Default Clause DEFAULT NULL n If a DEFAULT clause is not provided, the column definition acts as if DEFAULT NULL has been declared. NOT-NULL n If NULL is the default value for a column, then the NOT-NULL constraint cannot be part of the column definition. n Most commonly used default values include  ‘0’ in numeric columns  “Unknown” for a missing string value  “System timestamp” to mark a transaction, etc. n NULL n NULL cannot be the default value for a PRIMARY KEY column, even though DEFAULT NULL PRIMARY KEY is allowed. n Built-in functions can be specified as the default values.

11 n Syntax: column constraint ::= [CONSTRAINT constraint_name] NOT NULL | UNIQUE/PK specification REFERENCES specification | CHECK constraint definition n Constraint rules, as defined in a table creation statement, enforce data-integrity constraints on columns. n All the (new/modified) rows in the table are validated against them. Column Constraints in CREATE TABLE: Column Constraints

12 Column Constraints (Oracle 8i)

13 n A constraint forbids the use of NULLs in a column; NOT NULL constraint requires that a column receives a value during insert or update operations n If there is a (i) NOT NULL constraint and (ii) no default value is specified on a column, then a value must be entered into the column n NULL is a special value in SQL that belongs to all data types. n The interpretation of a NULL: missing, unknown, inapplicable, and miscellaneous, and NULLs cause a lot of irregular features in SQL, e.g. the strange 3-valued logic n Example. CREATE TABLE items (Item_num INTEGER, Menu_code CHAR(3) NOT NULL, Descrip CHAR(20)); Column Constraints in CREATE TABLE - NOT NULL

14 Column Constraints (Oracle 8i)

15 n Syntax: unique specification ::= UNIQUE | PRIMARY KEY n UNIQUE constraint states that no duplicate values are allowed in the column n Differences between UNIQUE and PRIMARY KEY: 1) There can be only one PRIMARY KEY but many UNIQUE columns 2) PRIMARY KEY is automatically declared to have a NOT NULL constraint, but a UNIQUE column can have NULL value Example. CREATE TABLE Account (Acct_num INTEGER PRIMARY KEY, Acct_code INTEGER UNIQUE); Column Constraints in CREATE TABLE: Unique & Primary Key

16 n When a PRIMARY KEY constraint is created, the DBS automatically creates an internal index on the column(s). n Multiple-column of the form, which means that the combination of a number of columns is unique, is allowed, e.g., PRIMARY KEY(Account_Number, Customer_Name) Example. CREATE TABLE depositor (Acct_num char(10), Customer_name char(15), PRIMARY KEY(Acct_num, Customer_name)); Column Constraints in CREATE TABLE: Unique & Primary Key A Table-definition constraint, not a Column-definition constraint

17 Column Constraints (Oracle 8i)

18 n Syntax: reference specificationreferenced table name reference column ::= REFERENCES [( )]  If no is specified, then the PRIMARY KEY column of the referenced table is assumed to be the target. n Specify referential integrity (foreign key integrity) n Example. CREATE TABLE account (Account# char(10), Branch_Name char(15) REFERENCES branch, Balance number(4, 2), PRIMARY KEY(Account#)); n Several columns can reference the same target column. n A PRIMARY KEY value cannot be deleted from the referenced table if it is referenced in a referencing table (without cascading). Column Constraints in CREATE TABLE: REFERENCE OR CREATE TABLE account (Account# char(10), Branch_Name char(15), Balance number(4, 2), PIMARY KEY(Account#), FOREIGN KEY (Branch_Name) REFERENCES branch);

19 n REFERENCE Clauses with ON DELETE CASCADE n Use the ON DELETE CASCADE option to specify the deletion from the referencing table when the corresponding referenced rows are deleted from the referenced table. n Reduces the quantity of SQL statements that are required for performing the delete operations. n Example. CREATE TABLE depositor (Acct_num CHAR(10) REFERENCES account ON DELETE CASCADE, Customer_name CHAR(15), Bname CHAR(15) REFERENCES branch (Branch_name) ON DELETE SET NULL, PRIMARY KEY(Acct_num, Customer_name); Column Constraints in CREATE TABLE: REFERENCE

20 n Default values for the Referenced Column:  If the referenced table is different from the referencing table, then by default, the referenced column is the primary-key column of the referenced table.  If the referenced and referencing tables are the same, then the referenced column must be specified. n Referential Relationships within a Table  A referential relationship between two columns of the same table can be established, e.g., CREATE TABLE Employee (Emp_num INTEGER, Mgr_num INTEGER REFERENCES Employee (Emp_num), PRIMARY KEY(Emp_num)); Column Constraints in CREATE TABLE : REFERENCE

21 n The column referenced by a FOREIGN KEY can be either a PRIMARY KEY or a column with a UNIQUE constraint. n In SQL-92, the following constraints are equivalent: PRIMARY KEY  CHECK (UNIQUE (SELECT FROM )) AND ( IS NOT NULL) UNIQUE  CHECK(UNIQUE (SELECT FROM )) NOT NULL  CHECK( IS NOT NULL) Column Constraints in CREATE TABLE: References

22 Column Constraints (Oracle 8i)

23 n Syntax: check constraint constraintsearch condition ::= CHECK n Tests the rows of a table against a logical expression, which is called search condition  Rejects rows whose search condition returns FALSE.  Accepts rows when the search condition returns TRUE (or in other implementations, UNKNOWN, a “benefit-of-the doubt" feature). n Range checking, e.g., CHECK(rating BETWEEN 1 AND 10) n Checking on values in enumerated sets, e.g., CHECK(Color IN (‘Red’, ‘Blue’, ‘Orange’, ‘Green’, ‘Yellow’)) n Subqueries cannot be specified in a CHECK clause Column Constraints in CREATE TABLE : Check Constraint

24 n Usage: associate one or more columns in a table with a CHECK constraint.  Example. CREATE TABLE Multi-Ref (Acct_Id CHAR(10), Loan_Amt INTEGER, Credit INTEGER, CHECK (Credit > 0 AND Loan_Amt < 9999), CHECK (Credit > Loan_Amt)); n (In some DBMSs) When the constraint is created on a number of columns  the columns cannot be assigned any default values, and  referential relationships cannot be established between them Column Constraints in CREATE TABLE: Multiple-Column

25 Column Constraints (Oracle 8i)

26 n Optional in a check constraint clause, but is a good idea to use it. n Constraint names appear in error messages when corresponding constraint violations occur. Examples. CREATE TABLE account (Account# char(10), Branch_Name char(15), Balance number(4, 2), CONSTRAINT Min_Balance CHECK (balance >= 0));  When a constraint is created, the DBS adds a row for that constraint to the system catalog table.  CHECK() clause allows complex expressions to be specified that verify relationships among rows/tables/constants. Constraint Names in CREATE TABLE CREATE TABLE depositor (Account# char(10), Customer_Name char(15), CONSTRAINT Acct_Verification CHECK To_NUMBER(Account#) BETWEEN 1 AND 9999));

27 SQL: ALTER TABLE

28 SQL: ALTER TABLE n Use the ALTER TABLE statement to update (add, delete, modify) the definition of (columns in) a table. ALTER TABLE ALTER TABLE Action ALTER TABLE ALTER TABLE Action ::= Column Definition ADD ( ) | DROP COLUMN [CASCADE CONSTRAINTS] | DROP CONSTRAINT Column Definition MODIFY ( ) | Constraint_State MODIFY CONSTRAINT | … n Add Column  Extends the existing table by putting a new, unique column on it.  Example. ALTER TABLE Account ADD Customer_ID CHAR(5) DEFAULT ‘00000’ NOT NULL;

29 ADD Table-Constraint Option (Oracle 8i)

30 ALTER TABLE: Add Table Constraints n Specify a new constraint in a table n Some DBMS requires the usage of ALTER TABLE statements to add referential integrity constraints to a table, rather than allowing the declaration be made at schema creation time. n Example. ALTER TABLE Account ADD FOREIGN KEY(Branch_name) REFERENCES Branch ADD PRIMARY KEY(Account_number) ADD CONSTRAINT Pos_Bal CHECK (Balance > 0);

31 Drop-Column Option (Oracle 8i)

32 ALTER TABLE: Drop Column n Removes an existing column from a table. n CASCADE CONSTRAINTS drops all referential integrity constraints defined on the dropped columns that are either primary or unique keys. n Without the CASCADE CONSTRAINTS clause, if any constraint is referenced by  columns from other tables, or  remaining columns in the same table, the DROP COLUMN statement aborts and an error is returned.  Example. ALTER TABLE Account DROP COLUMN Customer_ID CASCADE CONSTRAINTS;

33 Drop-Constraint Clause (Oracle 8i)

34 ALTER TABLE: Drop Constraint n Drop an existing constraint in a table:  Default values, (NOT-)NULLs, Primary Key, Unique, etc.  If the modified column is referenced by other tables, then those referential constraints could not be dropped, unless the CASCADE clause is specified.  To restore the constraints to the referencing tables again, e.g., foreign key, use the Alter Table statement.  Example. ALTER TABLE Branch DROP PRIMARY KEY CASCADE;

35 Column Constraints (Oracle 8i) Column_constraints: Foreign_Key Clause:

36 Cascading Actions in SQL n If there is a chain of foreign-key dependencies across multiple relations, with on delete cascade specified for each dependency, a deletion or update at one end of the chain can propagate across the entire chain. constraint violation n If a cascading update to delete causes a constraint violation that cannot be handled by a further cascading operation, the system aborts the transaction.  As a result, all the changes caused by the transaction and its cascading actions are undone. n Referential integrity is only checked at the end of a transaction  Intermediate steps are allowed to violate referential integrity provided later steps remove the violation  Otherwise, it would be impossible to create some database states, e.g., insert two tuples whose foreign keys point to each other (e.g., spouse attribute of relation married-person)

37 Cascading Actions in SQL n An example on specifying cascading actions in SQL: CREATE TABLE account... FOREIGN KEY(branch-name) REFERENCES branch ON DELETE CASCADE ON UPDATE CASCADE... ) n Due to the ON DELETE CASCADE clauses, if a deletion of a tuple in branch results in referential-integrity constraint violation, the delete “cascades” to the account relation will delete the tuple that refers to the branch. n Cascading updates are similar.

38 n Alternative to cascading:  on delete set null  on delete set default n Null values in foreign key attributes complicate SQL referential integrity semantics, and are best prevented using not null Cascading Actions in SQL

39 Modify-Column Option (Oracle 8i) Column_Constraint: Column Definition:

40 ALTER TABLE: Modify Column n Changes an existing column and its definition n Exactly what can be modified vary from DBMS to DBMS n Some of the updates that can be made in Oracle 8i:  modify a data type to a compatible data type, e.g., INTEGER to REAL  allow NULL by changing NOT NULL (or DEFAULT) to NULL  add NOT NULL constraint clause  Example. ALTER TABLE Account Modify (Balance number(5,2) DEFAULT 0, Branch_name NOT NULL);

41 ALTER TABLE: NULL Values n One can modify an existing column that did not permit NULLs to permit NULLs.  Example. ALTER TABLE Account MODIFY Customer_ID CHAR(6) NULL;  One can change a column from “allows NULL values” to “disallow NULL values,” provided that the column contains no NULL values.  Example. See example on previous slides.  Alternative: one can permit a non-NULL column to allow NULLs by using the DROP CONSTRINT clause to drop the NOT-NULL constraint on the column.

42 Modify Constraint State Option (Oracle 8i)

43 ALTER TABLE: Modify Constraint State n Modify Constraint constraint_name Constraint_State n Modify an existing constraint named constraint in a table to a new constraint state.  Possible constraint states: Enable/Disable Validate/No Validate Initially Immediate/Deferred  Example. ALTER TABLE Depositor MODIFY CONSTRAINT Acct_verification ENABLE;

44 SQL: Char Functions n Substr(String, m, [, n]) n Extract a substring of String, beginning at position m.  The extracted substring is of length n.  If n is omitted, then the default is the substring from position m to the end of String.  Example. Let String = ‘ABCDE’. Then substr(String, 2, 3) = ‘BCD’, and substr(String, 4) = ‘DE’