Top Banner
Dr. Chen, Oracle Database System (Oracle) 1 Oracle_ch3 HW (#7 & 8) SQL> --7. SQL> CREATE TABLE book_pricing (id, cost, retail, category) 2 AS (SELECT isbn, cost, retail, category 3 FROM books); Table created. SQL> --7b.(version 2) SQL> SQL> DROP TABLE book_pricing CASCADE CONSTRAINTS; Table dropped. SQL> SQL> CREATE TABLE book_pricing 2 AS (SELECT isbn as id, cost, retail, category 3 FROM books); Table created.
44

Chapter 4 Constraints

Feb 15, 2016

Download

Documents

Lance

Chapter 4 Constraints. Jason C. H. Chen , Ph.D. Professor of MIS School of Business Gonzaga University Spokane, WA 99258 USA [email protected]. What will we study today?. Data. Integrity. How to achieve it?. Referential Integrity. …. …. Objectives. - PowerPoint PPT Presentation
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Chapter 4 Constraints

Dr. Chen, Oracle Database System (Oracle) 1

Oracle_ch3 HW (#7 & 8)

SQL> --7.SQL> CREATE TABLE book_pricing (id, cost, retail, category) 2 AS (SELECT isbn, cost, retail, category 3 FROM books);

Table created.SQL> --7b.(version 2)SQL> SQL> DROP TABLE book_pricing CASCADE CONSTRAINTS;

Table dropped.

SQL> SQL> CREATE TABLE book_pricing 2 AS (SELECT isbn as id, cost, retail, category 3 FROM books);

Table created.

Page 2: Chapter 4 Constraints

Dr. Chen, Oracle Database System (Oracle) 2

SQL> --8.SQL> ALTER TABLE book_pricing 2 SET UNUSED (category);Table altered.

SQL> -- use one of the following commands to verify the resultSQL> SQL> --8aSQL> DESCRIBE book_pricing; Name Null? Type ----------------------------------------- -------- ---------------------------- ID VARCHAR2(10) COST NUMBER(5,2) RETAIL NUMBER(5,2)SQL> --8bSQL> SELECT * FROM book_pricing;

ID COST RETAIL ---------- ---------- ---------- 1059831198 18.75 30.95 0401140733 14.2 22 4981341710 37.8 59.95 8843172113 31.4 55.95 3437212490 12.5 19.95 3957136468 47.25 75.95 1915762492 21.8 25 9959789321 37.9 54.5 2491748320 48 89.95 0299282519 19 28.75 8117949391 5.32 8.95

ID COST RETAIL ---------- ---------- ---------- 0132149871 17.85 29.95 9247381001 15.4 31.95 2147428890 21.85 39.95

14 rows selected.

Page 3: Chapter 4 Constraints

Dr. Chen, Oracle Database System (Oracle) 3

What will we study today?

IntegrityData

… … ReferentialIntegrity

(Constraints)

How to achieve it?

Page 4: Chapter 4 Constraints

Dr. Chen, Oracle Database System (Oracle) 4

Chapter 4Constraints

Jason C. H. Chen, Ph.D.Professor of MIS

School of BusinessGonzaga University

Spokane, WA 99258 [email protected]

Page 5: Chapter 4 Constraints

Dr. Chen, Oracle Database System (Oracle) 5

Objectives

• Explain the purpose of constraints in a table• Distinguish among PRIMARY KEY, FOREIGN

KEY, UNIQUE, CHECK, and NOT NULL constraints and the appropriate use for each constraint

• Understand how constraints can be created when creating a table or modifying an existing table

• Distinguish between creating constraints at the column level and table level

Page 6: Chapter 4 Constraints

Dr. Chen, Oracle Database System (Oracle) 6

Objectives (continued)

• Create PRIMARY KEY constraints for a single column and a composite primary key (cpk)

• Create a FOREIGN KEY constraint• Create a UNIQUE constraint• Create a CHECK constraint• Create a NOT NULL constraint using the ALTER

TABLE…MODIFY command• Include constraints during table creation• Use DISABLE and ENABLE commands• Use the DROP command

Page 7: Chapter 4 Constraints

Dr. Chen, Oracle Database System (Oracle) 7

Referential Integrity• Move to JLDB_Referential_Integrity.pptx

file

Page 8: Chapter 4 Constraints

Dr. Chen, Oracle Database System (Oracle) 8

customers

orders

pk

fkpk

customer# LastName … Referred Region1001 MORALES NULL SE… …

1005 GIRARD NULL NW1020 FALAH NULL NE

Order# customer# … ShipZip ShipCost1000 1005 98114 2.00… … …

1003 1001 32328 4.001012 1007 49002 6.00

Can we “create” orders#1 if customers#5 is not created? Why?

Can we “delete” customers#5 if orders#1 is still in the database? Why?

Customers#5

orders#1

Referential Integrity

Page 9: Chapter 4 Constraints

Dr. Chen, Oracle Database System (Oracle) 9

Refresh the Database

• 1. Create a new folder on c:\ as follows:c:\oradata\chapter4

• 2. Go to Blackboard and download data files from Oracle chapter4 and save under c:\oradata\chapter4\

• 3. Run the following script file– Start c:\oradata\chapter4\JLDB_Build_4.sql

Page 10: Chapter 4 Constraints

Dr. Chen, Oracle Database System (Oracle) 10

Type the following SQL commands

-- chapter 4, Figure 4-5; p. 108INSERT INTO customers (customer#, lastname,

firstname, region)VALUES (1020, 'PADDY', 'JACK', 'NE');--extra INSERT commandINSERT INTO orders (order#, customer#, orderdate)VALUES (1021, 1021, '06-APR-09');-- DELETE commandDELETE FROM customersWHERE customer# = 1005;

Page 11: Chapter 4 Constraints

Dr. Chen, Oracle Database System (Oracle) 11

Constraint Checked with Data Input

Figure 4-5 Insert a row to test the constraintWhat cause the problem?

Page 12: Chapter 4 Constraints

Dr. Chen, Oracle Database System (Oracle) 12

customers

RULES: 1. You can’t add a record to TABLE- (or the table with fk, e.g., orders)

unless there is a corresponding record in TABLE-1 (or the table with pk).

2. You can’t delete a record in TABLE-1 (or the table with pk, e.g., customers) if there is a record in TABLE- (or the table with fk).

Order of entering data into the database: customers orders Order of deleting data from the database: orders customers

orders

pk

fkpk

customer# LastName … Referred Region1001 MORALES NULL SE… …

1005 GIRARD NULL NW1020 FALAH NULL NE

Order# customer# … ShipZip ShipCost1000 1005 98114 2.00… … …

1003 1001 32328 4.001012 1007 49002 6.00

Using the FOREIGN KEY ConstraintReferential Integrity

Page 13: Chapter 4 Constraints

Dr. Chen, Oracle Database System (Oracle) 13

Review from Last Class

What are the three rules of naming table and field?

What are the three (total of four) required information that should be described for each field?

1. Name 2. Type3. Size4. Constraint

L

(saved in “UPPER” case in the D.B.)

Page 14: Chapter 4 Constraints

Dr. Chen, Oracle Database System (Oracle) 14

What is a Constraint?

• A rule used to enforce business rules, practices, and policies

• A rule used to ensure accuracy and integrity of data

• A mechanism used to protect – the relationship between data within an Oracle

table, or– the correspondence between data in two different

tables.– For example, the state entered must be one of the 50

states in the U.S.

Page 15: Chapter 4 Constraints

Dr. Chen, Oracle Database System (Oracle) 15

Types of Constraints

• Integrity constraints: define primary and foreign keys

• Value constraints: define specific data values or data ranges that must be inserted into columns and whether values must be unique or not NULL

• Table constraint: restricts the data value with respect to all other values in the table

• Field (column) constraint: limits the value that can be placed in a specific field, irrespective of values that exist in other table records

Page 16: Chapter 4 Constraints

Dr. Chen, Oracle Database System (Oracle) 16

I. Naming conventions for constraints

<tablename>_<fieldname>_<constraint id>Where <constraint id> is:

• pk PRIMARY KEY• fk REFERENCES <tablename> (pk)• ck CHECK <condition to be checked>

(note that cc stands for CHECK CONDITION)• nn NOT NULL• uk UNIQUE

Inte

grai

tyco

nstr

aint

Valu

eco

nstr

aint

e.g., s_id NUMBER (6) CONSTRAINT student_s_id_pk PRIMARY KEY;

Page 17: Chapter 4 Constraints

Dr. Chen, Oracle Database System (Oracle) 17

Integrity Constraints

• Define primary key fields

•Specify foreign keys and their corresponding table and column references

•Specify composite keys

Page 18: Chapter 4 Constraints

Dr. Chen, Oracle Database System (Oracle) 18

Creating a Table

CREATE TABLE tablename(fieldname1 data_type (size)

[CONSTRAINT constraint_name constraint_type], fieldname2 data_type (size),

…[CONSTRAINT constraint_name constraint_type,]

…);

Page 19: Chapter 4 Constraints

Dr. Chen, Oracle Database System (Oracle) 19

Creating Constraints

• When– During table creation– After table creation, by modifying the existing

table• How

– Column level approach– Table level approach

Page 20: Chapter 4 Constraints

Dr. Chen, Oracle Database System (Oracle) 20

Creating Constraints at the Column Level

• If a constraint is being created at the column level, the constraint applies to the column specified

Creating Constraints at the Table Level• Approach can be used to create any constraint type after all

table field definitions are completed except NOT NULL• Required if constraint is based on multiple columns

Figure 4-1 Syntax for creating a column-level constraint

Figure 4-2 Syntax for creating a table-level constraint

Page 21: Chapter 4 Constraints

Dr. Chen, Oracle Database System (Oracle) 21

Customer# LastName FirstName Address City State Zip Referred Region EmailNUMBER(4)

VARCHAR2(10) VARCHAR2(10)

VARCHAR2(20)

VARCHAR2(12) VARCHAR2(2)

VARCHAR2(5)

NUMBER(4)

CHAR(2) VARCHAR2(30)

Order# Customer# OrderDate ShipDate ShipStreet ShipCity ShipState ShipZip ShipCostNUMBER(4) NUMBER(4) DATE DATE VARCHAR2(18) VARCHAR2(15) VARCHAR2(2) NUMBER(4) NUMBER(4,2)

CREATE TABLE Customers(Customer# NUMBER(4),LastName VARCHAR2(10) NOT NULL,FirstName VARCHAR2(10) NOT NULL,Address VARCHAR2(20),City VARCHAR2(12),State VARCHAR2(2),Zip VARCHAR2(5),Referred NUMBER(4),Region CHAR(2),Email VARCHAR2(30), CONSTRAINT customers_customer#_pk PRIMARY KEY(customer#), CONSTRAINT customers_region_ck CHECK (region IN ('N', 'NW', 'NE', 'S', 'SE', 'SW', 'W', 'E')) );

CUSTOMERSpk

ORDERSfkpk

Optional (variable name)

Page 22: Chapter 4 Constraints

Dr. Chen, Oracle Database System (Oracle) 22

Qs

• Q: How to display (describe) the table structure you just created of “customers” table?

• A: _______________________• Q: Any constraint(s) displayed?• A: ____• Q: How to display them?• A:_

DESCRIBE customers;

SELECT constraint_name FROM user_constraints WHERE table_name=‘CUSTOMERS’;

NO! case is sensitive(UPPER case) Why?

Page 23: Chapter 4 Constraints

Dr. Chen, Oracle Database System (Oracle) 23

Customer# LastName FirstName Address City State Zip Referred Region EmailNUMBER(4)

VARCHAR2(10) VARCHAR2(10)

VARCHAR2(20)

VARCHAR2(12) VARCHAR2(2)

VARCHAR2(5)

NUMBER(4)

CHAR(2) VARCHAR2(30)

Order# Customer# OrderDate ShipDate ShipStreet ShipCity ShipState ShipZip ShipCostNUMBER(4) NUMBER(4) DATE DATE VARCHAR2(18) VARCHAR2(15) VARCHAR2(2) NUMBER(4) NUMBER(4,2)

CREATE TABLE Orders (Order# NUMBER(4), Customer# NUMBER(4), OrderDate DATE NOT NULL, ShipDate DATE, ShipStreet VARCHAR2(18), ShipCity VARCHAR2(15), ShipState VARCHAR2(2), ShipZip VARCHAR2(5),ShipCost NUMBER(4,2), CONSTRAINT orders_order#_pk PRIMARY KEY(order#), CONSTRAINT orders_customer#_fk FOREIGN KEY (customer#) REFERENCES customers(customer#));

CUSTOMERSpk

ORDERSfkpk

Optional (variable name)

Page 24: Chapter 4 Constraints

Dr. Chen, Oracle Database System (Oracle) 24

Order# Customer# OrderDate ShipDate ShipStreet ShipCity ShipState ShipZip ShipCostNUMBER(4) NUMBER(4) DATE DATE VARCHAR2(18) VARCHAR2(15) VARCHAR2(2) NUMBER(4) NUMBER(4,2)

ORDERS

Order# Item# ISBN Quantity PaidEachNUMBER(4) NUMBER(2) VARCHAR2(10) NUMBER(3) NUMBER(5,2)

ORDERITEMS

CREATE TABLE ORDERITEMS ( Order# NUMBER(4), Item# NUMBER(2), ISBN VARCHAR2(10), Quantity NUMBER(3) NOT NULL, PaidEach NUMBER(5,2) NOT NULL, CONSTRAINT orderitems_order#item#_pk PRIMARY KEY (order#, item#), CONSTRAINT orderitems_order#_fk FOREIGN KEY (order#) REFERENCES orders (order#) , CONSTRAINT orderitems_isbn_fk FOREIGN KEY (isbn) REFERENCES books (isbn) , CONSTRAINT oderitems_quantity_ck CHECK (quantity > 0) );

ISBN Title PubDate PubID Cost Retail Discount CategoryVARCHAR2(10) VARCHAR2(30) DATE NUMBER(2) NUMBER(5,2) NUMBER(5,2) NUMBER(4,2) VARCHAR2(12)

BOOKSpk

fkfk

pk

Optional (variable name)

cpk

How to define ‘composite” key?

Page 25: Chapter 4 Constraints

Dr. Chen, Oracle Database System (Oracle) 25

Your Job

• You need to study and understand all CREATE TABLE SQL commands in JLDB_Build_4.sql

Page 26: Chapter 4 Constraints

Dr. Chen, Oracle Database System (Oracle) 26

Enforcement of Constraints

• All constraints are enforced at the table level

• If a data value violates a constraint, the entire row is rejected

Page 27: Chapter 4 Constraints

Dr. Chen, Oracle Database System (Oracle) 27

Constraint Types

Table 4-1 Constraint types

Page 28: Chapter 4 Constraints

Dr. Chen, Oracle Database System (Oracle) 28

Your Turn …

Page 29: Chapter 4 Constraints

Dr. Chen, Oracle Database System (Oracle) 29

Syntax:CONSTRAINT constraint_name PRIMARY KEY

Primary Key Constraints

SQL> CREATE TABLE students2 (s_id NUMBER(6) CONSTRAINT students_s_id_pk PRIMARY KEY,3 s_name VARCHAR2(30),4 s_class CHAR(2),5 s_dob DATE);

Create a table with the following information:1. Name of the table: students2. Fields: s_id number with 6 digits and is a primary key, s_name

character with 30 chars, s_class with 2 chars, s_dob with DATE

Page 30: Chapter 4 Constraints

Dr. Chen, Oracle Database System (Oracle) 30

at the Column-Level

Primary Key Constraints (cont.)

SQL> CREATE TABLE students2 (s_id NUMBER(6), 3 s_name VARCHAR2(30),4 s_class CHAR(2),5 s_dob DATE,6 CONSTRAINT students_s_id_pk PRIMARY KEY (s_id));

SQL> CREATE TABLE students2 (s_id NUMBER(6) CONSTRAINT students_s_id_pk PRIMARY KEY,3 s_name VARCHAR2(30),4 s_class CHAR(2),5 s_dob DATE);

Practice: Type in one of the command.

at the Table-Level

Page 31: Chapter 4 Constraints

Dr. Chen, Oracle Database System (Oracle) 31

Your Job

• Read the rest of powerpoint slide and practice all examples

• Skip to another practice example with THREE new tables

Page 32: Chapter 4 Constraints

Dr. Chen, Oracle Database System (Oracle) 32

Adding Constraints to Existing Tables

• Constraints are added to an existing table with the ALTER TABLE command

• Add a NOT NULL constraint using MODIFY clause

• All other constraints are added using ADD clause

Page 33: Chapter 4 Constraints

Dr. Chen, Oracle Database System (Oracle) 33

Using the PRIMARY KEY Constraint

• Ensures that columns do not contain duplicate or NULL values

• Only one per table is allowed

Figure 4-3 Syntax of the ALTER TABLE command to add a PRIMARY KEY constraint

Page 34: Chapter 4 Constraints

Dr. Chen, Oracle Database System (Oracle) 34

Drop Contraint

ALTER TABLE orderitemsDROP CONSTRAINT

orderitems_order#item#_pk PRIMARY KEY (order#, item#);

Page 35: Chapter 4 Constraints

Dr. Chen, Oracle Database System (Oracle) 35

Deletion of Foreign Key Values

• You cannot delete a value in a parent table referenced by a row in a child table

• Use ON DELETE CASCADE keywords when creating FOREIGN KEY constraint – it automatically deletes a parent row when the row in a child table is deleted

Page 36: Chapter 4 Constraints

Dr. Chen, Oracle Database System (Oracle) 36

Practice …

• Let’s try to create additional tables– JustLee Books would like to create some new

tables to store office equipment inventory data.

DeptIDDnameFax

DEPTEquipIDEdescPurchdateRatingDeptIDEtypeID

EQUIP

EtypeIDEtypename

ETYPES

Figure 4-26 E-R model for equipment tables

Page 37: Chapter 4 Constraints

Dr. Chen, Oracle Database System (Oracle) 37

Including Constraints during Table Creation

DeptIDDnameFax

DEPTEquipIDEdescPurchdateRatingDeptIDEtypeID

EQUIP

EtypeIDEtypename

ETYPES

• Each department name must be unique.• Each department must be assigned a name .

• Each equipment type name must be unique• Each equipment type must be assigned a name.• Each equipment item must be assigned a valid department.• If an equipment item is assigned a type, it must be a valid type.• Valid rating values for equipment are A, B, and C.

uniqueNOT NULL

uniqueNOT NULL

ck

fk fk

pkpk pk

Page 38: Chapter 4 Constraints

Dr. Chen, Oracle Database System (Oracle) 38

-- chapter 4, Figure 4-27; p. 122CREATE TABLE dept(deptid NUMBER(2), dname VARCHAR2(20) NOT NULL, fax VARCHAR2(12), CONSTRAINT dept_deptid_pk PRIMARY KEY (deptid), CONSTRAINT dept_dname_uk UNIQUE (dname) );

DEPT table creation

• Each department name must be unique.• Each department must be assigned a name .

uniqueNOT NULL

Page 39: Chapter 4 Constraints

Dr. Chen, Oracle Database System (Oracle) 39

-- chapter 4, Figure 4-27; p. 122CREATE TABLE dept(deptid NUMBER(2), dname VARCHAR2(20) NOT NULL, fax VARCHAR2(12), CONSTRAINT dept_deptid_pk PRIMARY KEY (deptid), CONSTRAINT dept_dname_uk UNIQUE (dname) );

-- chapter 4, Figure 4-30; p. 124CREATE TABLE dept(deptid NUMBER(2) CONSTRAINT dept_deptid_pk PRIMARY KEY, dname VARCHAR2(20) NOT NULL CONSTRAINT dept_dname_uk UNIQUE, fax VARCHAR2(12));

Constraints are defined at the column-level

What is the main difference on the following “CREATE TABLE” statements?

Constraints are defined at the table-level

Page 40: Chapter 4 Constraints

Dr. Chen, Oracle Database System (Oracle) 40

-- chapter 4, Figure 4-28; p. 123CREATE TABLE etypes(etypeid NUMBER(2), etypename VARCHAR2(20) NOT NULL, CONSTRAINT etypes_etypeid_pk PRIMARY KEY (etypeid), CONSTRAINT etypes_etypename_uk UNIQUE (etypename) );

-- chapter 4, Figure 4-29; p. 123CREATE TABLE equip(equipid NUMBER(3), edesc VARCHAR2(30), purchdate DATE, rating CHAR(1), deptid NUMBER(2) NOT NULL, etypeid NUMBER(2), CONSTRAINT equip_equipid_pk PRIMARY KEY (equipid), CONSTRAINT equip_deptid_fk FOREIGN KEY (deptid) REFERENCES dept (dept_id), CONSTRAINT equip_etypeid_fk FOREIGN KEY (etypeid) REFERENCES etypes (etypeid), CONSTRAINT equip_rating_ck CHECK (rating IN ('A', 'B', 'C', 'D')) );

• Each equipment item must be assigned a valid department.• If an equipment item is assigned a type, it must be a valid

type.• Valid rating values for equipment are A, B, and C.

• Each equipment type name must be unique• Each equipment type must be assigned a name.

Page 41: Chapter 4 Constraints

Dr. Chen, Oracle Database System (Oracle) 41

• HW!!• Practice all the examples in the text.• A Script file is available on the Bb (file name:

Ch4Queries.sql)• After completing all examples, do the HW (hint: see

the tables below for the final schema and the sample output on the Bb under “Assignments”

rep_id last first comm base_salaryNUMBER(5) VARCHAR2(15) VARCHAR2(10) CHAR(1) NUMBER(7,2)

store_id name contact rep_idNUMBER(8) VARCHAR2(30) VARCHAR2(30) NUMBER(5)

store_id name quarter rep_idNUMBER(8) VARCHAR2(5) CHAR(3) NUMBER(5)

pk store_reps

pk fkbook_stores

cpk, fk cpk cpk, fkrep_contracts

Page 42: Chapter 4 Constraints

Dr. Chen, Oracle Database System (Oracle) 42

Homework - Hands-On Assignments

Read and Practice all examples on Chapters 4• 1. Run the script files (in the folder \oradata\

chapter4\): JLDB_Build_4.sql• 2. Read Oracle assignment and create a script file

Oracle_ch4_Lname_Fname.sql for questions (#1 to #8; p.133) on “Hands-on Assignments”. .

• 3. Execute and test one problem at a time and make sure they are all running successfully.

• 4. When you done, spool the script files (see next slide for spooling instructions) and UPLOAD both *.sql and spooled file Oracle_ch4_Spool_Lname_Fname.txt to Bb by the midnight before the next class.

• Turn in a hardcopy of spooled file (*.txt ONLY) to me in the class.

Upload the SQL and spooled files (*.sql and *.txt) to the Bb (under “Assignments & Projects”) by the deadline

[correction on p.138: Name Datatype should be VARCHAR2(5)]

Page 43: Chapter 4 Constraints

Dr. Chen, Oracle Database System (Oracle) 43

How to Spool your Script and Output FilesAfter you tested the script file of Oracle_ch4_Lname_Fname.sql successfully,

follow the instructions below to spool both script and output files:Step 0. Run the following script file from SQL*Plus (since you have created

JLDB tables)– Start c:\oradata\chapter4\JLDB_Build_4.sql

• 1. type the following on SQL>– Spool c:\oradata\Oracle_ch4_Spool_Lname_Fname.txt (make sure your name is entered)

• 2. open Oracle_ch4_Lname_Fname.sql that you already tested• 3. copy and paste all the SQL commands (including all comments) to the

SQL*PLUS • 4. type Spool Off on the SQL>The output should contain your personal information, all SQL commands and

their solution on the .txt file and saved in C: drive (oradata\ folder)

Upload the SQL and spooled files (*.sql and *.txt) to the Bb (under “Assignments & Projects”) by the deadline

Page 44: Chapter 4 Constraints

Dr. Chen, Oracle Database System (Oracle) 44

• End of chapter 4