3 copyright © 2006, oracle. all rights reserved. relational data model part ii
TRANSCRIPT
3Copyright © 2006, Oracle. All rights reserved.
Relational Data Model Part II
3.2 - 2
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.
3.2 - 3
NOT NULL Constraint
Ensures that null values are not permitted for a column.
NOT NULL constraint(No row can containa null value forthis column.)(business rule)
Absence of NOT NULL constraint (Any row can contain a null value for this column.)
NOT NULL Constraint(business rule)
…
3.2 - 4
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 :
3.2 - 5
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), ...);
3.2 - 6
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), ...);
3.2 - 7
UNIQUE Constraint
EmployeesUNIQUE constraint
INSERT INTO
Not allowed: already exists
Allowed
…
case 1 : case 2 :
PRIMARY KEY
3.2 - 8
UNIQUE Constraint
CREATE TABLE Employees( emp_id CHAR(6), l_name VARCHAR(25) NOT NULL, email VARCHAR(25), CONSTRAINT emp_email_uk UNIQUE(email));
• Table-level constraint:
3.2 - 9
DEPARTMENTS
EMPLOYEESFOREIGNKEY
INSERT (a new employee)
PRIMARYKEY
Not allowed(9 does not exist) : R1
Allowedcase 1:
case 2:
FOREIGN KEY Constraint
90
3.2 - 10
FOREIGN KEY Constraint
CREATE TABLE Employees( emp_id CHAR(6), l_name VARCHAR(25) NOT NULL, email 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_email_uk UNIQUE(email));
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
3.2 - 11
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.
3.2 - 12
CREATE TABLE: Example
CREATE TABLE Employees( emp_id CHAR(6), f_name VARCHAR(20) NOT NULL, l_name VARCHAR(25) NOT NULL, email 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_email_uk UNIQUE (email), CONSTRAINT emp_dept_id_fk FOREIGN KEY (dept_id) REFERENCES Departments(dept_id));
3.2 - 13
University Database(Representation of Referential Integrity)
3.2 - 14
Creating University Database (CREATE TABLE Student & Course)
CREATE TABLE Student( StdSSN CHAR(11), StdFirstName VARCHAR(50), StdLastName VARCHAR(50), StdCity VARCHAR(50), StdState CHAR(2), StdZip CHAR(10), StdClass CHAR(6), StdGPA DECIMAL(3,2), CONSTRAINT Student_pk PIMARY KEY (StdSSN));
CREATE TABLE Course( CourseNo CHAR(6), CrsDesc VARCHAR(250), CrsUnits CHAR(2), CONSTRAINT Course_pk PRIMARY KEY (CourseNo));
3.2 - 15
Creating University Database(CREATE TABLE Faculty)
CREATE TABLE Faculty( FacSSN CHAR(11), FacFirstName VARCHAR(50) NOT NULL, FacLastName VARCHAR(50) NOT NULL, FacCity VARCHAR(50) NOT NULL, FacState CHAR(2) NOT NULL, FacZipCode CHAR(10) NOT NULL, FacHireDate DATE, CONSTRAINT Faculty_pk PRIMARY KEY (FacSSN));
3.2 - 16
Creating University Database(CREATE TABLE Offering)
CREATE TABLE Offering( OfferNo CHAR(6), CourseNo CHAR(6) NOT NULL, OffTerm CHAR(6) NOT NULL, OffYear INTEGER NOT NULL, OffLocation VARCHAR(50), OffDays CHAR(6), OffTime DATE, FacSSN CHAR(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));
3.2 - 17
Creating University Database(CREATE TABLE Enrollment)
CREATE TABLE Enrollment( StdSSN CHAR(11) , OfferNo NUMBER(6) , EnrGrade NUMBER(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)
);
3.2 - 18
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
3.2 - 19
Self-Referencing Example
EmpSSN EmpFirstName EmpLastName EmpRank EmpSalary EmpSupervisor
098-76-5432 LEONARD VINCE ASST $35,000 654-32-1098
543-21-0987 VICTORIA EMMANUEL PROF $120,000
654-32-1098 LEONARD FIBON ASSC $70,000 543-21-0987
876-54-3210 CRISTOPHER COLAN ASST $40,000 654-32-1098
123-45-6789 JOHN SMITH ASSC $75,000 543-21-0987
Table Name: Employee
FKPK
543-21-0987
654-32-1098
098-76-5432 876-54-3210
123-45-6789
record self-referencingarchitecture
3.2 - 20
Self-Referencing Example
CREATE TABLE Employee( EmpSSN CHAR(11), EmpFirstName VARCHAR(50) NOT NULL, EmpLastName VARCHAR(50) NOT NULL, EmpCity VARCHAR(50) NOT NULL, EmpState CHAR(2) NOT NULL, EmpZipCode CHAR(10) NOT NULL, EmpHireDate DATE, EmpSupervisor CHAR(11), CONSTRAINT employee_pk PRIMARY KEY (FacSSN), CONSTRAINT employee_fk
FOREIGN KEY (EmpSupervisor) REFERENCES Employee (EmpSSN));
3.2 - 21
Graphical Representation of Self-Referencing
MS Access can only indirectly show self-referencing relationship.
3.2 - 22
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 CrsDesc CrsUnits
IS320 FUNDAMENTALS OF BUSINESS PROGRAMMING 4
IS460 SYSTEMS ANALYSIS 4
IS470 BUSINESS DATA COMMUNICATIONS 4
IS480 FUNDAMENTALS OF DATABASE MANAGEMENT 4
OfferNo CourseNo OffLocation OffTime OffDays
1111 IS320 BLM302 10:30 AM MW
1234 IS320 BLM302 10:30 AM MW
5678 IS480 BLM302 10:30 AM MW
Table Name: Offering
Table Name: Course
3.2 - 23
When to Ensure Referential Integrity?
• When deleting a referenced row
• When updating the PK of a referenced row
CourseNo CrsDesc CrsUnits
IS320 FUNDAMENTALS OF BUSINESS PROGRAMMING 4
IS460 SYSTEMS ANALYSIS 4
IS470 BUSINESS DATA COMMUNICATIONS 4
IS480 FUNDAMENTALS OF DATABASE MANAGEMENT 4
OfferNo CourseNo OffLocation OffTime OffDays
1111 IS320 BLM302 10:30 AM MW
1234 IS320 BLM302 10:30 AM MW
5678 IS480 BLM302 10:30 AM MW
Table Name: Offering
Table Name: Course
3.2 - 24
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
3.2 - 25
SQL Syntax Example of Possible Actions(For Ensuring Referential Integrity)
CREATE TABLE Enrollment( OfferNo NUMBER(6) NOT NULL, StdSSN CHAR(11) NOT NULL, EnrGrade NUMBER(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.
3.2 - 26
Update Operations On Tables
• INSERT a record.
• DELETE a record.
• UPDATE a record
• Integrity constraints should not be violated by these
update operations.
3.2 - 27
CREATE TABLE: Employees
CREATE TABLE Employees( emp_id CHAR(6), f_name VARCHAR(20) NOT NULL, l_name VARCHAR(25) NOT NULL, email 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_email_uk UNIQUE (email), 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);
3.2 - 28
UPDATE employees *ERROR at line 1:ORA-02291: integrity constraint (employees.emp_dept_id_fk) violated - parent key not found
UPDATE employeesSET dept_id = 55WHERE dept_id = 110;
Example of Violating Constraints(UPDATE records)
The message shows that department 55 does not exist in parent table Department.
3.2 - 29
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 departmentsWHERE 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.
3.2 - 30
The INSERT Operation (INSERT a record)
• Violate entity integrity (Rejected)
Because NOT NULL constraint on SSN is violated. Why ?
INSERT INTO EMPLOYEEVALUES (’Cecilia’, ’F’, ’Kolonsky’, null, ’1960-01-01’, ’123 Riley Street’, ’M’, 40000, null, 4);
PK
3.2 - 31
The INSERT Operation (INSERT a record)
• Violate the PK constraint (Rejected)
Because UNIQUE constraint is violated. Why ?.
INSERT INTO EMPLOYEEVALUES (’Alicia’, ’J’, ’Zelaya’, ’999887777’,
’1960-04-05’, ’6357 Windy Lane, Katy, TX’, ’F’, 2800, ’987654321’, 4);
3.2 - 32
The INSERT Operation (INSERT a record)
• Violate the referential integrity constraint (Rejected) Why? Because Department No 7 does not exist.
INSERT INTO EMPLOYEEVALUES (’Cecilia’, ’F’, ’Kolonsky’, ‘677678989’, ’1960-01-01’, ‘123 Riley Street’, ’M’, 40000, ‘987654321’, 7 );
FK
3.2 - 33
The INSERT Operation (INSERT a record)
• Are all constraints satisfied?
INSERT INTO EMPLOYEEVALUES (’Cecilia’, ’F’, ’Kolonsky’, ‘677678989’ , ’1960-01-01’, ‘123 Riley Street’, ’M’, 40000, null, 4 );
3.2 - 34
The DELETE Operation (DELETE child records)
• This deletion is acceptable. DELETE RESTRICT, OK ?
DELET FROM WORK_ONWHERE ESSN = ’999887777’;
Child table
Parent table
FK
3.2 - 35
The DELETE Operation
(DELETE a referenced parent record)
• This deletion is not acceptable , if ….
DELET FROM EMPLOYEEWHERE SSN = ’999887777’;
Child table
Parent table
A referenced row
The FK of child table is ON DELETE RESTRICT
3.2 - 36
The UPDATE Operation(Update non-PK, non-FK Column)
• This operation is acceptable.
UPDATE EMPLOYEESET SALARY = 28000WHERE SSN = ’999887777’;
3.2 - 37
The UPDATE Operation(Update FK Column of Child Table)
• This operation is acceptable.
UPDATE EMPLOYEESET DNO = 1WHERE SSN = ’999887777’;
Child/Parent table
Parent/Child table PK
PK
FK
FK
3.2 - 38
The UPDATE Operation (Update FK Column of Child Table)
• Unacceptable, because it violates referential integrity constraint. Why ?
UPDATE EMPLOYEESET DNO = 7WHERE SSN = ’999887777’;
Child/Parent table
Parent/Child table PK
PK
FK
FK
3.2 - 39
The UPDATE Operation (Update PK Column of Parent Table)
• Unacceptable, because it violates PK constraints (entity integrity). Why ?
UPDATE EMPLOYEESET SSN = ’999887777’WHERE SSN = ’987654321’;
Child/Parent table
Parent/Child table PK
PK
FK
FK
3.2 - 40
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).
3.2 - 41
分組專題(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)