bordoloi database design: relational model dr. bijoy bordoloi

54
Bordoloi Bordoloi Database Design: Database Design: Relational Model Relational Model Dr. Bijoy Bordoloi Dr. Bijoy Bordoloi

Upload: erik-fox

Post on 27-Dec-2015

226 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: Bordoloi Database Design: Relational Model Dr. Bijoy Bordoloi

BordoloiBordoloi

Database Design: Relational Database Design: Relational ModelModel

Dr. Bijoy BordoloiDr. Bijoy Bordoloi

Page 2: Bordoloi Database Design: Relational Model Dr. Bijoy Bordoloi

BordoloiBordoloi

Relational DatabaseRelational Database

• A relational database is a database that is A relational database is a database that is perceived by its users as a set of tables and perceived by its users as a set of tables and nothing but tablesnothing but tables

Page 3: Bordoloi Database Design: Relational Model Dr. Bijoy Bordoloi

BordoloiBordoloi

Relational ModelRelational Model• Tabular data structureTabular data structure - table, row, column, data - table, row, column, data

type, null valuetype, null value

• Eight operatorsEight operators - restrict, project, join, union, - restrict, project, join, union, difference, intersect, product, dividedifference, intersect, product, divide

• Integrity rulesIntegrity rules - primary and foreign keys, entity - primary and foreign keys, entity integrity, referential integrityintegrity, referential integrity

• Three parts of relational model correspond to Three parts of relational model correspond to information, process, and integrity disciplines of information, process, and integrity disciplines of software engineeringsoftware engineering

Page 4: Bordoloi Database Design: Relational Model Dr. Bijoy Bordoloi

BordoloiBordoloi

Data StructureData Structure• Table approximates the formal term relation Table approximates the formal term relation

and the physical fileand the physical file

• Row approximates the formal term tuple and Row approximates the formal term tuple and the physical recordthe physical record

• Column approximates the formal term Column approximates the formal term attribute and the physical fieldattribute and the physical field

• Data type approximates the formal term Data type approximates the formal term domaindomain

Page 5: Bordoloi Database Design: Relational Model Dr. Bijoy Bordoloi

BordoloiBordoloi

Characteristics 0f a Relation Characteristics 0f a Relation (Table) (Table)

• The order of rows and columns immaterial.The order of rows and columns immaterial.• All values are atomic – each row/column intersection represents All values are atomic – each row/column intersection represents

a single value. In other words, ‘repeating groups’ are not a single value. In other words, ‘repeating groups’ are not allowed.allowed.

• Every value in a column must be a member of a conceptual set of Every value in a column must be a member of a conceptual set of atomic values called a domain.atomic values called a domain.

• A value may be null, that is, not known or inapplicable• A relation, A relation, by definitionby definition, cannot have duplicate rows. Every table , cannot have duplicate rows. Every table

mustmust have a ‘Primary Key’ which guarantees that there are no have a ‘Primary Key’ which guarantees that there are no duplicate rows (discussed in depth later).duplicate rows (discussed in depth later).

Page 6: Bordoloi Database Design: Relational Model Dr. Bijoy Bordoloi

Data StructureData Structure

EMP

EMP_NBR EMP_NME DEPT# SAL HRE_DTE

012 SMITH 25 20000 10/26/1984

007 BOND 01 29000 09/01/1983

127 JONES 25 62000 05/14/1969

061 CLARKE 17 45000 04/01/1978

065 CUMMINGS 17 33000 06/12/1981

032 SIMPSON 01 95000 09/15/1986

099 CROCKET 25 46000 01/03/1990

COLUMN_NAME NNNNNNNNAME

ROW

ATOMIC DATA VALUES DOMAIN

TABLE NAME

Page 7: Bordoloi Database Design: Relational Model Dr. Bijoy Bordoloi

BordoloiBordoloi

Example: Repeating GroupsExample: Repeating Groups

Page 8: Bordoloi Database Design: Relational Model Dr. Bijoy Bordoloi

BordoloiBordoloi

Importance of Attribute Domain Importance of Attribute Domain and Data Typesand Data Types

• A relational DBMS can relate A relational DBMS can relate any data field in one table any data field in one table to any data field in another to any data field in another table as long as the two table as long as the two tables share a data field tables share a data field that is defined on the same that is defined on the same ‘domain’ (the same data ‘domain’ (the same data type).type).

Page 9: Bordoloi Database Design: Relational Model Dr. Bijoy Bordoloi

BordoloiBordoloi

Attribute Domain and Data TypesAttribute Domain and Data Types

• Consider the the following two tables, Consider the the following two tables, Student and Employee. Do these tables Student and Employee. Do these tables share any ‘common’ columns?share any ‘common’ columns?

Student:Student:

Employee:Employee:

SSN (Number (9))SSN (Number (9)) St_Name (Char (16))St_Name (Char (16))

SSN (Char (9))SSN (Char (9)) E_Name (Char (22))E_Name (Char (22)) Phone (Number (10))Phone (Number (10))

Page 10: Bordoloi Database Design: Relational Model Dr. Bijoy Bordoloi

BordoloiBordoloi

Semantic Data TypesSemantic Data Types(User Definable Data Types)(User Definable Data Types)

• User-friendly data type namesUser-friendly data type names

• User-friendly value setsUser-friendly value sets

• Composite data types

Page 11: Bordoloi Database Design: Relational Model Dr. Bijoy Bordoloi

BordoloiBordoloi

Semantic Data TypesSemantic Data TypesCREATE DATATYPECREATE DATATYPE IDID [1 . . . 9999][1 . . . 9999]

CREATE DATATYPECREATE DATATYPE SOCSECSOCSEC INTEGERINTEGER

CREATE DATATYPECREATE DATATYPE SEXSEX [M, F][M, F]

CREATE DATATYPECREATE DATATYPE GIVENNAMEGIVENNAME CHAR (12)CHAR (12)

CREATE DATATYPECREATE DATATYPE FAMILYNAMEFAMILYNAME CHAR (25)CHAR (25)

CREATE DATATYPECREATE DATATYPE FULLNAMEFULLNAME (GIVENNAME,(GIVENNAME,

GIVENNAME,GIVENNAME,

FAMILYNAME)FAMILYNAME)

CREATE TABLE EMPLOYEE (CREATE TABLE EMPLOYEE (

EMP#EMP# IDID

SOCSECSOCSEC SOCSECSOCSEC

NAMENAME FULLNAMEFULLNAME

SEXSEX SEXSEX

. . . ). . . )

Page 12: Bordoloi Database Design: Relational Model Dr. Bijoy Bordoloi

BordoloiBordoloi

Checking for Compatible Data TypesChecking for Compatible Data Types

Operations combining different data types are disallowed inOperations combining different data types are disallowed in

general…general…

SELECTSELECT FNAME, LNAMEFNAME, LNAME

FROMFROM EMPLOYEEEMPLOYEE

WHEREWHERE EMP# = SOCSECEMP# = SOCSEC

……however DBMS might automatically convert physicalhowever DBMS might automatically convert physical

dimensions…dimensions…

……or user may define appropriate conversion proceduresor user may define appropriate conversion procedures

Page 13: Bordoloi Database Design: Relational Model Dr. Bijoy Bordoloi

BordoloiBordoloi

Benefits of Semantic Data TypesBenefits of Semantic Data Types

• Automatic validation of column values and Automatic validation of column values and checking for compatible data types checking for compatible data types reduces reduces errorserrors..

• Data type names provide Data type names provide additional additional semantic informationsemantic information for users. for users.

• ProductivityProductivity benefits of composite data benefits of composite data types.types.

Page 14: Bordoloi Database Design: Relational Model Dr. Bijoy Bordoloi

BordoloiBordoloi

Null ValuesNull Values

• Null – a special symbol, independent of Null – a special symbol, independent of data type, which means either data type, which means either unknownunknown or or inapplicableinapplicable..

• Result of Result of comparison operatorscomparison operators is null when is null when either argument is null.either argument is null.

• Result of Result of arithmetic operatorsarithmetic operators is null when is null when either argument is null.either argument is null.

Page 15: Bordoloi Database Design: Relational Model Dr. Bijoy Bordoloi

BordoloiBordoloi

Examples of Operations on NullsExamples of Operations on Nulls Table: CompensationTable: Compensation

EMP#EMP# JOBCODEJOBCODE SALARY SALARY COMMISSIONCOMMISSION

E10E10 SALES SALES 12500 12500 32090 32090

E11E11 NULL NULL 25000 25000 8000 8000

E12E12 SALES SALES 44000 44000 0 0

E13E13 SALES SALES 44000 44000 NULL NULL

E14E14 PROG PROG 19500 19500 NULL NULL

E15E15 CLERK CLERK NULL NULL NULL NULL

Page 16: Bordoloi Database Design: Relational Model Dr. Bijoy Bordoloi

BordoloiBordoloi

Examples of Operations on NullsExamples of Operations on Nulls

What is the output of the following query?What is the output of the following query?

SELECTSELECT EMP#EMP#

FROMFROM COMPENSATIONCOMPENSATION

WHEREWHERE JOBCODE = “SALES” JOBCODE = “SALES”

AND AND (SALARY + COMMISSION) > 30000(SALARY + COMMISSION) > 30000

Page 17: Bordoloi Database Design: Relational Model Dr. Bijoy Bordoloi

BordoloiBordoloi

Table Definition in SQL (DB2)Table Definition in SQL (DB2)• CREATE TABLE EMPLOYEE (CREATE TABLE EMPLOYEE (• EMP#EMP# SMALLINT NOT NULL,SMALLINT NOT NULL,• SOCSECSOCSEC INTEGER,INTEGER,• FNAMEFNAME VARCHAR (12) NOT NULL,VARCHAR (12) NOT NULL,• LNAMELNAME VARCHAR (25) NOT NULL,VARCHAR (25) NOT NULL,• SEXSEX CHAR (1),CHAR (1),• SPOUSESPOUSE SMALLINT,SMALLINT,• SALARYSALARY FLOAT,FLOAT,• JOBCODEJOBCODE VARCHAR (6),VARCHAR (6),• DIVNAMEDIVNAME VARCHAR (12) NOT NULL,VARCHAR (12) NOT NULL,• DEPT#DEPT# SMALLINT NOT NULLSMALLINT NOT NULL• ))

• Each column has a name that is unique within the table Each column has a name that is unique within the table and is specified to store a specific type of data and is specified to store a specific type of data including whether NULL values are allowed or not.including whether NULL values are allowed or not.

Page 18: Bordoloi Database Design: Relational Model Dr. Bijoy Bordoloi

BordoloiBordoloi

Oracle: NOT NULL ConstraintOracle: NOT NULL Constraint

• A NOT NULL constraint means that a data row A NOT NULL constraint means that a data row must have a value for the column specified as must have a value for the column specified as NOT NULL.NOT NULL.

• A fairly standard practice is to assign each A fairly standard practice is to assign each constraint a constraint a unique constraint name.unique constraint name.

• In Oracle, if constraints are not named, then In Oracle, if constraints are not named, then Oracle assigns meaningless system-generated Oracle assigns meaningless system-generated names to each constraint. names to each constraint.

Page 19: Bordoloi Database Design: Relational Model Dr. Bijoy Bordoloi

BordoloiBordoloi

Oracle Example: Not Null ConstraintOracle Example: Not Null Constraint

fname fname VARCHAR2(15)VARCHAR2(15)

CONSTRAINT nn_emp_last_name CONSTRAINT nn_emp_last_name NOT NULL,NOT NULL,

lnamelname VARCHAR2(25)VARCHAR2(25)

CONSTRAINT nn_emp_first_name CONSTRAINT nn_emp_first_name NOT NULL,NOT NULL,

Page 20: Bordoloi Database Design: Relational Model Dr. Bijoy Bordoloi

BordoloiBordoloi

Characteristics 0f a Relation Characteristics 0f a Relation (Table) (Table)

• The order of rows and columns immaterial.The order of rows and columns immaterial.• All values are atomic – each row/column intersection represents All values are atomic – each row/column intersection represents

a single value. In other words, ‘repeating groups’ are not a single value. In other words, ‘repeating groups’ are not allowed.allowed.

• Every value in a column must be a member of a conceptual set of Every value in a column must be a member of a conceptual set of atomic values called a domain.atomic values called a domain.

• A value may be null, that is, not known or inapplicable• A relation, A relation, by definitionby definition, cannot have duplicate rows. Every table , cannot have duplicate rows. Every table

mustmust have a ‘Primary Key’ which guarantees that there are no have a ‘Primary Key’ which guarantees that there are no duplicate rows (discussed in depth later).duplicate rows (discussed in depth later).

Page 21: Bordoloi Database Design: Relational Model Dr. Bijoy Bordoloi

BordoloiBordoloi

KEYSKEYS

Relational DBMS uses associative addressing.Relational DBMS uses associative addressing.– Identify and locate rows by valueIdentify and locate rows by value– Physical address is transparent to userPhysical address is transparent to user

Page 22: Bordoloi Database Design: Relational Model Dr. Bijoy Bordoloi

BordoloiBordoloi

KEYSKEYS

A B C

C Z

C X Y

ASSOCIATIVE ADDRESSING

A B C

Z *

X Y *

PHYSICAL ADDRESSING

**

Page 23: Bordoloi Database Design: Relational Model Dr. Bijoy Bordoloi

BordoloiBordoloi

KEYSKEYS

• Associative addressing is simpler for the Associative addressing is simpler for the end-user.end-user.

• Physical data independence – storage Physical data independence – storage structures and access paths are transparent structures and access paths are transparent to user and application programsto user and application programs

Page 24: Bordoloi Database Design: Relational Model Dr. Bijoy Bordoloi

BordoloiBordoloi

KEYSKEYS• Associative addressing is based on keys – a column, or Associative addressing is based on keys – a column, or

group of columns, used to identify rows.group of columns, used to identify rows.• Simple key – a key formed from a single columnSimple key – a key formed from a single column• Composite key – a key formed from several columnsComposite key – a key formed from several columns• The relational model has five kinds of keysThe relational model has five kinds of keys

• SuperSuper• CandidateCandidate• PrimaryPrimary• Alternate (secondary)Alternate (secondary)• ForeignForeign

Page 25: Bordoloi Database Design: Relational Model Dr. Bijoy Bordoloi

BordoloiBordoloi

KEYSKEYS

• In relational DBMS, a key is not the In relational DBMS, a key is not the same as an index!same as an index!

Keys identify rows (logical design)Keys identify rows (logical design)

Indexes locate rows (physical design)Indexes locate rows (physical design)

Page 26: Bordoloi Database Design: Relational Model Dr. Bijoy Bordoloi

BordoloiBordoloi

Candidate KeysCandidate Keys

• Candidate Key – any (simple or composite) Candidate Key – any (simple or composite) column of a table which is both column of a table which is both unique and unique and minimalminimal..

• Uniqueness – no two rows in a table may have Uniqueness – no two rows in a table may have same candidate key value same candidate key value at any timeat any time..

• Minimality – every column of a composite Minimality – every column of a composite candidate key must be necessary for uniqueness.candidate key must be necessary for uniqueness.

Page 27: Bordoloi Database Design: Relational Model Dr. Bijoy Bordoloi

BordoloiBordoloi

Primary KeyPrimary Key• Primary Key – a candidate key chosen by the database Primary Key – a candidate key chosen by the database

designer to identify rows of a table in queriesdesigner to identify rows of a table in queries• The primary key is the only guaranteed way to identify The primary key is the only guaranteed way to identify

rows in queriesrows in queriesUPDATEUPDATE COMPENSATIONCOMPENSATIONSETSET SALARY = 30000SALARY = 30000WHEREWHERE EMP# = E3EMP# = E3

• Primary keys must be Primary keys must be unique, minimal, non-null, unique, minimal, non-null, and and preferably preferably time-invarianttime-invariant..

• Alternate key – any candidate key which is not a Alternate key – any candidate key which is not a primary key – may have null values.primary key – may have null values.

Page 28: Bordoloi Database Design: Relational Model Dr. Bijoy Bordoloi

BordoloiBordoloi

Candidate Keys/Primary KeyCandidate Keys/Primary Key

• Assume every employee has a phone#, only one phone# , and must Assume every employee has a phone#, only one phone# , and must have a phone# and that no two employees share the same phone#. have a phone# and that no two employees share the same phone#.

• What is(are) the Candiadate Key(s)?What is(are) the Candiadate Key(s)?• What would you choose as the Primary Key of table EMPLOYEE?What would you choose as the Primary Key of table EMPLOYEE?

EMPLOYEE

EMP-ID SS-NUM EMP- NAME PHONE

Page 29: Bordoloi Database Design: Relational Model Dr. Bijoy Bordoloi

BordoloiBordoloi

Primary KeyPrimary Key• The Primary Key MUST of course be a The Primary Key MUST of course be a

DeterminantDeterminant- i.e., all the other non-key attributes of a table - i.e., all the other non-key attributes of a table must be must be functionally dependentfunctionally dependent on the primary on the primary key.key.

• In other words, for any given value of the primary In other words, for any given value of the primary key, one should get one and only value of the one key, one should get one and only value of the one non-key attributesnon-key attributes

Page 30: Bordoloi Database Design: Relational Model Dr. Bijoy Bordoloi

BordoloiBordoloi

Functional DependencyFunctional Dependency• ExampleExample

– SOC_SEC_NBR EMP_NMESOC_SEC_NBR EMP_NME

SOC_SEC_NBRSOC_SEC_NBR EMP_NMEEMP_NME

-One and only one EMP_NME for a specific SOC_SEC_NBROne and only one EMP_NME for a specific SOC_SEC_NBR- SOC_SEC_NBR is theSOC_SEC_NBR is the determinantdeterminant of EMP_NME of EMP_NME - EMP_NME is functionally EMP_NME is functionally dependentdependent on SOC_SEC_NBR on SOC_SEC_NBR

Page 31: Bordoloi Database Design: Relational Model Dr. Bijoy Bordoloi

BordoloiBordoloi

Determinants and Keys Determinants and Keys What is (are) the determinant (s)?What is (are) the determinant (s)?What is (are) the candidate key (s)? What is (are) the candidate key (s)? What is the primary key? What is the primary key?

TTable: Student-Dorm-Feeable: Student-Dorm-FeeSIDSID DORMDORM FEEFEE

101101 OracleOracle 10001000

102102 OracleOracle 10001000

103103 DB2DB2 800800

104104 DB2DB2 800800

105105 SybaseSybase 500500

Page 32: Bordoloi Database Design: Relational Model Dr. Bijoy Bordoloi

BordoloiBordoloi

Primary KeyPrimary Key

• Assume every employee must have a phone# , can have Assume every employee must have a phone# , can have more than one phone #, and more than one employee more than one phone #, and more than one employee share the same phone#. share the same phone#.

• What is the Primary Key?What is the Primary Key?

EMPLOYEE

EMP-ID SS-NUM EMP- NAME PHONE

Page 33: Bordoloi Database Design: Relational Model Dr. Bijoy Bordoloi

BordoloiBordoloi

Primary KeyPrimary Key

• Assume every employee must have a phone# , can have Assume every employee must have a phone# , can have more than one phone #, but no two employees can share more than one phone #, but no two employees can share the same phone#. the same phone#.

• What is the Primary Key?What is the Primary Key?

EMPLOYEE

EMP-ID SS-NUM EMP- NAME PHONE

Page 34: Bordoloi Database Design: Relational Model Dr. Bijoy Bordoloi

BordoloiBordoloi

Entity IntegrityEntity Integrity

• Entity Integrity – If the primary key (PK) is Entity Integrity – If the primary key (PK) is a composite key then all columns of the a composite key then all columns of the primary key must be primary key must be non-null.non-null.

• The primary key is the only The primary key is the only guaranteed way to positively guaranteed way to positively identify rows in queriesidentify rows in queries

Page 35: Bordoloi Database Design: Relational Model Dr. Bijoy Bordoloi

BordoloiBordoloi

QuestionsQuestions

• What What similaritiessimilarities and and differencesdifferences do you do you find between find between an Entityan Entity and a and a TableTable??

Page 36: Bordoloi Database Design: Relational Model Dr. Bijoy Bordoloi

BordoloiBordoloi

Foreign KeysForeign Keys

• Foreign key – a (simple or composite) Foreign key – a (simple or composite) column which refers to the primary key of column which refers to the primary key of somesome table in a database. table in a database.

• Foreign and primary keys must be defined Foreign and primary keys must be defined on same data type.on same data type.

• A foreign key may be contained in a A foreign key may be contained in a primary key or another foreign key.primary key or another foreign key.

Page 37: Bordoloi Database Design: Relational Model Dr. Bijoy Bordoloi

BordoloiBordoloi

Foreign Keys DefinedForeign Keys Defined EMP

EMP_NBR EMP_NME DEPT# SAL HRE_DTE 012 SMITH 25 20000 10/26/1984 007 BOND 01 29000 09/01/1983 127 JONES 25 62000 05/14/1969 061 CLARKE 17 45000 04/01/1978 065 CUMMINGS 17 33000 06/12/1981 032 SIMPSON 01 95000 09/15/1986 099 CROCKET 25 46000 01/03/1990

DEPT

DEPT# DEPT_NAME MGR_EMP_NBR

17 ACCOUNTING 007

12 MARKETING ?

25 LEGAL 099

A foreign key A foreign key is a column or is a column or

columns in a table columns in a table that matches a primary that matches a primary

key in some table key in some table in the database.in the database.

Are there any Are there any other foreign keys?other foreign keys?

Page 38: Bordoloi Database Design: Relational Model Dr. Bijoy Bordoloi

BordoloiBordoloi

In-Class ExerciseIn-Class Exercise

• To be handed out in classTo be handed out in class

Page 39: Bordoloi Database Design: Relational Model Dr. Bijoy Bordoloi

BordoloiBordoloi

Referential IntegrityReferential Integrity

• Referential Integrity – a foreign key which Referential Integrity – a foreign key which identifies primary key of table T must either identifies primary key of table T must either be be wholly nullwholly null or or match the value of the match the value of the primary keyprimary key of some row in T of some row in T

Page 40: Bordoloi Database Design: Relational Model Dr. Bijoy Bordoloi

BordoloiBordoloi

Rationale for Referential Integrity Rationale for Referential Integrity

• Any non-primary key column may be Any non-primary key column may be unknown or inapplicable (wholly null).unknown or inapplicable (wholly null).

• An unmatched non-null foreign key An unmatched non-null foreign key identifies a non-existent object and is in identifies a non-existent object and is in errorerror

Page 41: Bordoloi Database Design: Relational Model Dr. Bijoy Bordoloi

BordoloiBordoloi

Referential IntegrityReferential Integrity RulesRules ((Foreign Key Rules)Foreign Key Rules)

How is referential integrity maintained in a database?How is referential integrity maintained in a database?Some operations that may cause a violation …Some operations that may cause a violation …

– Insert of PK valuesInsert of PK values – no problem – no problem – Update of PK valuesUpdate of PK values – what happens to matching foreign keys? – what happens to matching foreign keys? – Delete of PK valuesDelete of PK values – what happens to matching foreign keys? – what happens to matching foreign keys?– Insert of FK valuesInsert of FK values – disallowed unless matching primary key – disallowed unless matching primary key

existsexists– Update of FK valuesUpdate of FK values – disallowed unless matching primary key – disallowed unless matching primary key

existsexists– Delete of FK values Delete of FK values (FK Values set to NULL) – no problem as (FK Values set to NULL) – no problem as

long as NULL values are allowed in the FKlong as NULL values are allowed in the FK

Page 42: Bordoloi Database Design: Relational Model Dr. Bijoy Bordoloi

BordoloiBordoloi

Referential Integrity RulesReferential Integrity Rules

So, for each FK in each table the database designer must specify:

• Whether or not NULLs allowed in the FK

• What should happen to the FK values should the related PK values in the PK table are deleted or updated

Page 43: Bordoloi Database Design: Relational Model Dr. Bijoy Bordoloi

BordoloiBordoloi

Null Rule AlternativesNull Rule Alternatives

• Nulls allowed in foreign key columns Nulls allowed in foreign key columns (minimum cardinality 0)(minimum cardinality 0)

• Nulls disallowed in foreign key columns Nulls disallowed in foreign key columns (minimum cardinality 1)(minimum cardinality 1)

Page 44: Bordoloi Database Design: Relational Model Dr. Bijoy Bordoloi

BordoloiBordoloi

Delete Rule AlternativesDelete Rule Alternatives

• Delete of primary key cascades to foreign Delete of primary key cascades to foreign keyskeys

• Delete of primary key nullifies foreign keysDelete of primary key nullifies foreign keys

• Delete of primary key is restricted if there Delete of primary key is restricted if there are any matching foreign keysare any matching foreign keys

Page 45: Bordoloi Database Design: Relational Model Dr. Bijoy Bordoloi

BordoloiBordoloi

Update Rule AlternativesUpdate Rule Alternatives

• Update of primary key cascades to foreign Update of primary key cascades to foreign keyskeys

• Update of primary key nullifies foreign Update of primary key nullifies foreign keyskeys

• Update of primary key is restricted if there Update of primary key is restricted if there are any matching foreign keysare any matching foreign keys

Page 46: Bordoloi Database Design: Relational Model Dr. Bijoy Bordoloi

BordoloiBordoloi

Rule Alternatives: MeaningRule Alternatives: Meaning(Oracle Syntax)(Oracle Syntax)

On Delete/Update Cascade:On Delete/Update Cascade: Any delete/update made to the PK table Any delete/update made to the PK table

should be cascaded through to the FK table. should be cascaded through to the FK table. NOTE:NOTE:If a PK value is deleted in the PK table then If a PK value is deleted in the PK table then all the rows in the FK table with matching all the rows in the FK table with matching FK values are also FK values are also deleteddeleted in entiretyin entirety..

Page 47: Bordoloi Database Design: Relational Model Dr. Bijoy Bordoloi

BordoloiBordoloi

Rule Alternatives: MeaningRule Alternatives: Meaning(Oracle Syntax)(Oracle Syntax)

On Delete/Update Set Null:On Delete/Update Set Null:Any PK values that are deleted/updated in Any PK values that are deleted/updated in the PK table, cause affected FK values in the PK table, cause affected FK values in the FK table to be set to null.the FK table to be set to null.

Unlike Unlike DeleteDelete CascadeCascade, the , the entireentire row row is is not not deleted, only the affected FK values are deleted, only the affected FK values are set to null. set to null.

Page 48: Bordoloi Database Design: Relational Model Dr. Bijoy Bordoloi

BordoloiBordoloi

Rule Alternatives: MeaningRule Alternatives: MeaningOn Delete/Update Restrict:On Delete/Update Restrict: Any updates made to the PK table that would Any updates made to the PK table that would

delete or change a primary key value will be delete or change a primary key value will be rejected unless no foreign key references that rejected unless no foreign key references that value in the FKvalue in the FK table(s).table(s).

In other words, you are In other words, you are restrictrestricted to deleting or ed to deleting or updating only those PK values in the PK table updating only those PK values in the PK table which do NOT appear as FK values. which do NOT appear as FK values. Example:Example:

Page 49: Bordoloi Database Design: Relational Model Dr. Bijoy Bordoloi

BordoloiBordoloi

Referential Integrity : ExamplesReferential Integrity : Examples

What might be the appropriate referential integrity rules for the tables Employee, Division and Department?

Page 50: Bordoloi Database Design: Relational Model Dr. Bijoy Bordoloi

BordoloiBordoloi

DocumentationDocumentation

• Database designer specifiesDatabase designer specifies– Primary keysPrimary keys– Alternate keysAlternate keys– Foreign keysForeign keys– Foreign key rules, for each foreign keyForeign key rules, for each foreign key– Semantic data typesSemantic data types– Default values (optional)Default values (optional)

Page 51: Bordoloi Database Design: Relational Model Dr. Bijoy Bordoloi

BordoloiBordoloi

Enhanced SQLEnhanced SQLCREATE TABLE TABLENAME ( COLUMNNAME DATATYPENAME NULLS [NOT] ALLOWED COLUMNNAME DATATYPENAME NULLS [NOT] ALLOWED . . . ) PRIMARY KEY COLUMNNAME ALTERNATE KEY COLUMNNAME ALTERNATE KEY COLUMNNAME FOREIGN KEY ( COLUMNNAME IDENTIFIES PKTABLE NULLS [NOT] ALLOWED DELETE OF PKTABLE [CASCADES] [RESTRICTED] [NULLIFIES] UPDATE OF PKTABLE [CASCADES] [RESTRICTED] [NULLIFIES] ) FOREIGN KEY ( . . . ) FOREIGN KEY ( . . . )

Page 52: Bordoloi Database Design: Relational Model Dr. Bijoy Bordoloi

BordoloiBordoloi

Example (DB2)Example (DB2)CREATE TABLE EMPLOYEE ( EMP# ID NOT NULL, SOCSEC SOCSEC, NAME FULLNAME, NOT NULL, SEX SEX, SPOUSE ID, SALARY MONEY, JOBCODE CHAR (16), DIVNAME VARCHAR (12), NOT NULL, DEPT# DEPARTMENT , NOT NULL ) PRIMARY KEY EMP# ALTERNATE KEY SOCSEC FOREIGN KEY ( SPOUSE IDENTIFIES EMPLOYEE NULLS ALLOWED DELETE OF EMPLOYEE NULLIFIES UPDATE OF EMPLOYEE CASCADES ) FOREIGN KEY ( (DIVNAME, DEPT#) IDENTIFIES DEPARTMENT NULLS NOT ALLOWED DELETE OF DEPARTMENT RESTRICTED UPDATE OF DEPARTMENT CASCADES )

Page 53: Bordoloi Database Design: Relational Model Dr. Bijoy Bordoloi

BordoloiBordoloi

Example (Oracle)Example (Oracle)CREATE TABLE EMPLOYEE ( EMP# ID CONSTRAINT pk_employee PRIMARY KEY, SOCSEC SOCSEC, NAME FULLNAME CONSTRAINT nn_emt_name NOT NULL, SEX SEX, SPOUSE ID

CONSTRAINT fk_emp_spouse FOREIGN KEY (spouse) REFERENCES Employee ON DELETE SET NULL,

SALARY MONEY, JOBCODE CHAR (16), DIVNAME VARCHAR (12), DEPT# DEPARTMENT,

CONSTRAINT fk_emp_dept FOREIGN KEY (divname, dept#) REFERENCES Department ON UPDATE CASCADE

);

Page 54: Bordoloi Database Design: Relational Model Dr. Bijoy Bordoloi

BordoloiBordoloi

IN-Class ExerciseIN-Class Exercise

• Distributed in classDistributed in class