3 Copyright © 2006, Oracle. All rights reserved. Relational Data Model Part II.

Slides:



Advertisements
Similar presentations
Data Definition and Integrity Constraints
Advertisements

Relational Database. Relational database: a set of relations Relation: made up of 2 parts: − Schema : specifies the name of relations, plus name and type.
The Relational Model. Introduction Introduced by Ted Codd at IBM Research in 1970 The relational model represents data in the form of table. Main concept.
OUTLINE OF THE LECTURE PART I GOAL: Understand the Data Definition Statements in Fig 4.1 Step1: Columns of the Tables and Data types. Step2: Single column.
SQL Lecture 10 Inst: Haya Sammaneh. Example Instance of Students Relation  Cardinality = 3, degree = 5, all rows distinct.
7 7 SQL Data Definition 4Spread throughout chapter 7.
Overview Begin 6:00 Quiz15 mins6:15 Review Table Terms25 mins6:40 Short Break10 mins6:50 SQL: Creating Tables60 mins7:50 Break10 mins8:00 Lab – Creating.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 3 The Basic (Flat) Relational Model.
10 Copyright © Oracle Corporation, All rights reserved. Including Constraints.
8 Copyright © Oracle Corporation, All rights reserved. Manipulating Data.
Relational Model Stores data as tables –Each column contains values about the same attribute –Each column has a distinct name –Each row contains values.
1 Relational Model. 2 Relational Database: Definitions  Relational database: a set of relations  Relation: made up of 2 parts: – Instance : a table,
SQL DDL constraints Restrictions on the columns and tables 1SQL DDL Constraints.
DAVID M. KROENKE’S DATABASE PROCESSING, 10th Edition © 2006 Pearson Prentice Hall 4-1 David M. Kroenke Database Processing Chapter 7 Structured Query Language.
McGraw-Hill/Irwin Copyright © 2007 by The McGraw-Hill Companies, Inc. All rights reserved. Chapter 3 The Relational Data Model.
Chapter 5 Relational Model Concepts Dr. Bernard Chen Ph.D. University of Central Arkansas.
Your Oracle Account UserName is the same as your UWP username Followed Not case sensitive Initial Password: UWPstudent Password is case sensitive.
Exam 2 Review Dr. Bernard Chen Ph.D. University of Central Arkansas.
Oracle Data Definition Language (DDL)
CS 380 Introduction to Database Systems (Chapter 5: The Relational Data Model and Relational Database Constraints)
Developing Data Models for Business Databases (Part II)
4 Copyright © Oracle Corporation, All rights reserved. Displaying Data from Multiple Tables.
Database. Basic Definitions Database: A collection of related data. Database Management System (DBMS): A software package/ system to facilitate the creation.
SQL Data Definition (CB Chapter 6) CPSC 356 Database Ellen Walker Hiram College (Includes figures from Database Systems by Connolly & Begg, © Addison Wesley.
SQL data definition using Oracle1 SQL Data Definition using Oracle.
Chapter 8 Part 1 SQL-99 Schema Definition, Constraints, Queries, and Views.
1 CSE 480: Database Systems Lecture 5: Relational Data Model.
Oracle Data Definition Language (DDL) Dr. Bernard Chen Ph.D. University of Central Arkansas Fall 2008.
10 Copyright © 2009, Oracle. All rights reserved. Using DDL Statements to Create and Manage Tables.
1 Copyright © 2006, Oracle. All rights reserved. Using DDL Statements to Create and Manage Tables.
Copyright © 2004, Oracle. All rights reserved. Using DDL Statements to Create and Manage Tables.
Copyright © 2011 by Michael V. Mannino All rights reserved. Database Design, Application Development, and Administration, 5 th Edition Chapter 3 The Relational.
Chapter 2 The Relational Data Model. McGraw-Hill/Irwin © 2004 The McGraw-Hill Companies, Inc. All rights reserved. Outline Relational model basics Integrity.
5 Copyright © 2006, Oracle. All rights reserved. Understanding Entity Relationship Diagrams ( 實體關係圖 ) Part I.
Lecture 2: Using DDL Statements to Create and Manage Tables & Indexes
FALL 2004CENG 351 File Structures and Data Management1 Relational Model Chapter 3.
10 Copyright © Oracle Corporation, All rights reserved. Including Constraints.
Slide Chapter 5 The Relational Data Model and Relational Database Constraints.
Recap of SQL Lab no 8 Advance Database Management System.
Creating Tables and Inserting Records -- Not easy to edit! -- check constraints! Create table test1 ( C1 char(5) primary key, C2 Varchar2(15) not null.
SQL Basics. What is SQL? SQL stands for Structured Query Language. SQL lets you access and manipulate databases.
CS 3630 Database Design and Implementation. Database Schema Branch (Bno…) Staff (Sno…Bno) Owner (Ono…) PropertyForRent (Pno…Ono) Renter (Rno…) Viewing.
Dec 8, 2003Murali Mani Constraints B term 2004: lecture 15.
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.
Introduction to Database System Adisak Intana Lecturer Chapter 7 : Data Integrity.
10 Copyright © Oracle Corporation, All rights reserved. Including Constraints.
Database Lab Lecture 1. Database Languages Data definition language ( DDL ) Data definition language –defines data types and the relationships among them.
Chapter 4 Constraints Oracle 10g: SQL. Oracle 10g: SQL 2 Objectives Explain the purpose of constraints in a table Distinguish among PRIMARY KEY, FOREIGN.
9 Copyright © 2004, Oracle. All rights reserved. Using DDL Statements to Create and Manage Schema Objects.
INCLUDING CONSTRAINTS lecture5. Outlines  What are Constraints ?  Constraint Guidelines  Defining Constraint  NOT NULL constraint  Unique constraint.
Chapter 9 Logical Database Design : Mapping ER Model To Tables.
CSE314 Database Systems Lecture 3 The Relational Data Model and Relational Database Constraints Doç. Dr. Mehmet Göktürk src: Elmasri & Navanthe 6E Pearson.
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.
Chapter 3: Relational Databases
SQL constrains and keys. SORTED RESULTS Sort the results by a specified criterion SELECT columns FROM tables WHERE predicates ORDER BY column ASC/DESC;
Chapter 2 The Relational Model. 2-2 In This Chapter You Will Learn   What a data model is and what its uses are   The terminology of the relational.
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.
Chapter 2 The Relational Data Model. Outline Relational model basics Integrity rules Rules about referenced rows Relational Algebra.
Database Constraints Ashima Wadhwa. Database Constraints Database constraints are restrictions on the contents of the database or on database operations.
SQL: Schema Definition and Constraints Chapter 6 week 6
CS 3630 Database Design and Implementation
Developing Data Models – Conversion Rules
CS4222 Principles of Database System
Oracle Data Definition Language (DDL)
Database Design: Relational Model
Including Constraints
Presentation transcript:

3 Copyright © 2006, Oracle. All rights reserved. Relational Data Model Part II

How to Include Constraints (Integrity Rules) When Creating Tables The following constraint types are valid in SQL: – NOT NULL – PRIMARY KEY – UNIQUE (Alternate Key) – FOREIGN KEY – CHECK Constraint name facilitates the identification of a constraint if a violation occurs when a data row is being inserted, updated or deleted.

NOT NULL Constraint Ensures that null values are not permitted for a column. NOT NULL constraint (No row can contain a null value for this column.) (business rule) Absence of NOT NULL constraint (Any row can contain a null value for this column.) NOT NULL Constraint (business rule) …

PRIMARY KEY Constraint Departments PRIMARY KEY INSERT (a new department) Not allowed (null value) Not allowed (not unique, 50 already exists) … case 1 : case 2 :

Defining Constraints (Examples for PRIMARY KEY and NULL Constraints) Column-level constraint: Table-level constraint: CREATE TABLE Employees ( emp_id CHAR(6) CONSTRAINT employee_pk PRIMARY KEY, f_name VARCHAR(20), job_id VARCHAR(10) NOT NULL,...); CREATE TABLE Employees ( emp_id CHAR(6), f_name VARCHAR(20), job_id VARCHAR(10) NOT NULL,..., CONSTRAINT employee_pk PRIMARY KEY (emp_id),... );

Defining Constraints (An Example for Composite Primary Key) Table-level constraint: CREATE TABLE Enrollment ( OfferNo INTEGER, StdSSN CHAR(11), EnGrade DECIMAL(3,2), CONSTRAINT PKEnrollment PRIMARY KEY ( OfferNo, StdSSN ),... );

UNIQUE Constraint Employees UNIQUE constraint INSERT INTO Not allowed: already exists Allowed … case 1 : case 2 : PRIMARY KEY

UNIQUE Constraint CREATE TABLE Employees ( emp_id CHAR(6), l_name VARCHAR(25) NOT NULL, VARCHAR(25), CONSTRAINT emp_ _uk UNIQUE( ) ); Table-level constraint:

DEPARTMENTS EMPLOYEES FOREIGN KEY INSERT (a new employee) PRIMARY KEY Not allowed (9 does not exist) : R1 Allowed case 1: case 2: FOREIGN KEY Constraint 90

FOREIGN KEY Constraint CREATE TABLE Employees ( emp_id CHAR(6), l_name VARCHAR(25) NOT NULL, VARCHAR(25), hire_date DATE NOT NULL, dept_id CHAR(4),..., CONSTRAINT emp_pk PRIMARY KEY (emp_id), CONSTRAINT emp_dept_id_fk FOREIGN KEY (dept_id) REFERENCES Departments(dept_id), CONSTRAINT emp_ _uk UNIQUE( )); CREATE TABLE Departments ( dept_id CHAR(4), dept_name VARCHAR(30) NOT NULL, loc_id CHAR(4), CONSTRAINT dept_pk PRIMARY KEY (dept_id) ); (dept_id) is optional in this case. Note: Create table Departments before table Employees

CREATE TABLE Employees ( emp_id CHAR(6), l_name VARCHAR(25) NOT NULL, salary INTEGER CONSTRAINT employees_salary_min_ck CHECK (salary > 0),... ); CHECK Constraint Defines a condition for a particular column, that each row must satisfy.

CREATE TABLE : Example CREATE TABLE Employees ( emp_id CHAR(6), f_name VARCHAR(20) NOT NULL, l_name VARCHAR(25) NOT NULL, VARCHAR(25) NOT NULL, hire_date DATE NOT NULL, salary INTEGER CONSTRAINT emp_salary_ck CHECK (salary > 0), commission_pct DECIMAL(2,2), dept_id INTEGER, CONSTRAINT emp_pk PRIMARY KEY (emp_id), CONSTRAINT emp_ _uk UNIQUE ( ), CONSTRAINT emp_dept_id_fk FOREIGN KEY (dept_id) REFERENCES Departments(dept_id) );

University Database (Representation of Referential Integrity)

Creating University Database (CREATE TABLE Student & Course) CREATE TABLE Student ( StdSSN CHAR(11), StdFirstNameVARCHAR(50), StdLastNameVARCHAR(50), StdCityVARCHAR(50), StdStateCHAR(2), StdZipCHAR(10), StdClassCHAR(6), StdGPADECIMAL(3,2), CONSTRAINT Student_pk PIMARY KEY (StdSSN) ); CREATE TABLE Course ( CourseNo CHAR(6), CrsDesc VARCHAR(250), CrsUnitsCHAR(2), CONSTRAINT Course_pk PRIMARY KEY (CourseNo) );

Creating University Database (CREATE TABLE Faculty) CREATE TABLE Faculty ( FacSSN CHAR(11), FacFirstNameVARCHAR(50) NOT NULL, FacLastNameVARCHAR(50) NOT NULL, FacCityVARCHAR(50) NOT NULL, FacStateCHAR(2) NOT NULL, FacZipCodeCHAR(10) NOT NULL, FacHireDateDATE, CONSTRAINT Faculty_pk PRIMARY KEY (FacSSN) );

Creating University Database (CREATE TABLE Offering) CREATE TABLE Offering ( OfferNo CHAR(6), CourseNoCHAR(6) NOT NULL, OffTermCHAR(6) NOT NULL, OffYearINTEGER NOT NULL, OffLocation VARCHAR(50), OffDaysCHAR(6), OffTimeDATE, FacSSNCHAR(11), CONSTRAINT Offering_pk PRIMARY KEY (OfferNo), CONSTRAINT Offering_CourseNo_fk FOREIGN KEY (CourseNo) REFERENCES Course (CourseNo), CONSTRAINT Offering_FacSSN_fk FOREIGN KEY (FacSSN) REFERENCES Faculty (FacSSN) );

Creating University Database (CREATE TABLE Enrollment) CREATE TABLE Enrollment ( StdSSNCHAR(11), OfferNo NUMBER(6), EnrGradeNUMBER(3), CONSTRAINT Enrollment_pk PRIMARY KEY (StdSSN, OfferNo), CONSTRAINT Enrollment_StdSSN_fk FOREIGN KEY (StdSSN) REFERENCES Student (StdSSN), CONSTRAINT Enrollment_OfferNo_fk FOREIGN KEY (OfferNo) REFERENCES Offering (OfferNo) );

Self-Referencing Relationships ( 自我參照關係 ) Foreign key that references the same table Represents relationships among records of the same table Not common but important in specialized situations

Self-Referencing Example EmpSSNEmpFirstNameEmpLastNameEmpRankEmpSalaryEmpSupervisor LEONARDVINCEASST$35, VICTORIAEMMANUELPROF$120, LEONARDFIBONASSC$70, CRISTOPHERCOLANASST$40, JOHNSMITHASSC$75, Table Name: Employee FK PK record self-referencing architecture

Self-Referencing Example CREATE TABLE Employee ( EmpSSN CHAR(11), EmpFirstNameVARCHAR(50) NOT NULL, EmpLastNameVARCHAR(50) NOT NULL, EmpCityVARCHAR(50) NOT NULL, EmpStateCHAR(2) NOT NULL, EmpZipCodeCHAR(10) NOT NULL, EmpHireDateDATE, EmpSupervisor CHAR(11), CONSTRAINT employee_pk PRIMARY KEY (FacSSN), CONSTRAINT employee_fk FOREIGN KEY (EmpSupervisor) REFERENCES Employee (EmpSSN) );

Graphical Representation of Self-Referencing MS Access can only indirectly show self-referencing relationship.

Referenced Rows ( 被參照的記錄 ) A row of a parent table is referenced if there are rows in a child table with FK values identical to its PK value of the row. CourseNo CrsDescCrsUnits IS320FUNDAMENTALS OF BUSINESS PROGRAMMING4 IS460SYSTEMS ANALYSIS4 IS470BUSINESS DATA COMMUNICATIONS4 IS480FUNDAMENTALS OF DATABASE MANAGEMENT4 OfferNo CourseNo OffLocationOffTimeOffDays 1111IS320BLM30210:30 AMMW 1234IS320BLM30210:30 AMMW 5678IS480BLM30210:30 AMMW Table Name: Offering Table Name: Course

When to Ensure Referential Integrity? When deleting a referenced row When updating the PK of a referenced row CourseNo CrsDescCrsUnits IS320FUNDAMENTALS OF BUSINESS PROGRAMMING4 IS460SYSTEMS ANALYSIS4 IS470BUSINESS DATA COMMUNICATIONS4 IS480FUNDAMENTALS OF DATABASE MANAGEMENT4 OfferNo CourseNo OffLocationOffTimeOffDays 1111IS320BLM30210:30 AMMW 1234IS320BLM30210:30 AMMW 5678IS480BLM30210:30 AMMW Table Name: Offering Table Name: Course

Possible Choices for Defining Related Tables (For Ensuring Referential Integrity) Restrict ( 限制 ) –Do not permit any action on the referenced parent row Cascade ( 連鎖 ) –Perform the same action on related child rows Nullify ( 空值化 ) –Set the foreign key of related child rows to null –Only valid if foreign keys accept null values Default ( 預設值 ) –Set the FK column of related child rows to its default value

SQL Syntax Example of Possible Actions (For Ensuring Referential Integrity) CREATE TABLE Enrollment ( OfferNoNUMBER(6) NOT NULL, StdSSNCHAR(11) NOT NULL, EnrGradeNUMBER(3,2), CONSTRAINT enrollment_pk PRIMARY KEY (OfferNo, StdSSN), CONSTRAINT enrollment_offerNo_fk FOREIGN KEY (OfferNo) REFERENCES Offering (OfferNo) ON DELETE RESTRICT ON UPDATE CASCADE, CONSTRAINT enrollment_stdSSN_fk FOREIGN KEY (StdSSN) REFERENCES Student (StdSSN) ON DELETE RESTRICT ON UPDATE CASCADE ); The actions can be specified in SQL using ON DELETE and ON UPDATE clauses. The clauses are part of FK constraints of the child table.

Update Operations On Tables INSERT a record. DELETE a record. UPDATE a record Integrity constraints should not be violated by these update operations.

CREATE TABLE : Employees CREATE TABLE Employees ( emp_id CHAR(6), f_name VARCHAR(20) NOT NULL, l_name VARCHAR(25) NOT NULL, VARCHAR(25) NOT NULL, hire_date DATE NOT NULL, salary INTEGER CONSTRAINT emp_salary_ck CHECK (salary > 0), commission_pct DECIMAL(2,2), dept_id INTEGER, CONSTRAINT emp_ _uk UNIQUE ( ), CONSTRAINT emp_pk PRIMARY KEY (emp_id), CONSTRAINT emp_dept_id_fk FOREIGN KEY (dept_id) REFERENCES Departments(dept_id) ON DELETE RESTRICT ON UPDATE CASCADE );

UPDATE employees * ERROR at line 1: ORA-02291: integrity constraint (employees.emp_dept_id_fk) violated - parent key not found UPDATE employees SET dept_id = 55 WHERE dept_id = 110; Example of Violating Constraints ( UPDATE records ) The message shows that department 55 does not exist in parent table Department.

Example of Violating Constraints ( DELETE a record ) You cannot delete a referenced row of a (parent) table if the FK of its child table is ON DELETE RESTRICT DELETE FROM departments WHERE dept_id = 60; DELETE FROM departments * ERROR at line 1: ORA-02292: integrity constraint (employees.emp_dept_id_fk) violated - child record found The message shows that department 60 has associated child records in child table employees.

The INSERT Operation ( INSERT a record ) Violate entity integrity (Rejected) Because NOT NULL constraint on SSN is violated. Why ? INSERT INTO EMPLOYEE VALUES (’Cecilia’, ’F’, ’Kolonsky’, null, ’ ’, ’123 Riley Street’, ’M’, 40000, null, 4); PK

The INSERT Operation ( INSERT a record ) Violate the PK constraint (Rejected) Because UNIQUE constraint is violated. Why ?. INSERT INTO EMPLOYEE VALUES (’Alicia’, ’J’, ’Zelaya’, ’ ’, ’ ’, ’6357 Windy Lane, Katy, TX’, ’F’, 2800, ’ ’, 4);

The INSERT Operation ( INSERT a record ) Violate the referential integrity constraint (Rejected) Why? Because Department No 7 does not exist. INSERT INTO EMPLOYEE VALUES (’Cecilia’, ’F’, ’Kolonsky’, ‘ ’, ’ ’, ‘123 Riley Street’, ’M’, 40000, ‘ ’, 7 ); FK

The INSERT Operation ( INSERT a record ) Are all constraints satisfied? INSERT INTO EMPLOYEE VALUES (’Cecilia’, ’F’, ’Kolonsky’, ‘ ’, ’ ’, ‘123 Riley Street’, ’M’, 40000, null, 4 );

The DELETE Operation ( DELETE child records ) This deletion is acceptable. DELETE RESTRICT, OK ? DELET FROM WORK_ON WHERE ESSN = ’ ’; Child table Parent table FK

The DELETE Operation ( DELETE a referenced parent record ) This deletion is not acceptable, if …. DELET FROM EMPLOYEE WHERE SSN = ’ ’; Child table Parent table A referenced row The FK of child table is ON DELETE RESTRICT

The UPDATE Operation (Update non-PK, non-FK Column) This operation is acceptable. UPDATE EMPLOYEE SET SALARY = WHERE SSN = ’ ’;

The UPDATE Operation (Update FK Column of Child Table) This operation is acceptable. UPDATE EMPLOYEE SET DNO = 1 WHERE SSN = ’ ’; Child/Parent table Parent/Child table PK FK

The UPDATE Operation (Update FK Column of Child Table) Unacceptable, because it violates referential integrity constraint. Why ? UPDATE EMPLOYEE SET DNO = 7 WHERE SSN = ’ ’; Child/Parent table Parent/Child table PK FK

The UPDATE Operation (Update PK Column of Parent Table) Unacceptable, because it violates PK constraints (entity integrity). Why ? UPDATE EMPLOYEE SET SSN = ’ ’ WHERE SSN = ’ ’; Child/Parent table Parent/Child table PK FK

The UPDATE Operation Updating an column that is neither a PK nor a FK usually causes no problems –Except UNIQUE, CHECK & NOT NULL Modifying a PK value is similar to deleting one record and inserting another in its place. If a FK of the child table is modified, the DBMS must make sure that the new value refers to an existing record in its parent table (or is null).

分組專題 (DDL: Data Definition Language) 下一週第一堂上課時交 分組專題 #1 第三章 71 頁 Problems : 1, 2, 3, 4, 5, 6 ( 使用 SQL:2003 語法 ) (SQL:2003 語法 : 參考第三章 74 頁 Appendix 3.B) ( 範例 : 參考第三章 73 頁 Appendix 3.A)