Data Integrity in Relational Model

advertisement
Data Integrity Rules within the
Relational Data Model
• What do we mean by integrity in this
context?
• Entity Integrity
• Referential Integrity
Entity integrity Rule
• A Primary Key must have a unique value &
null values are not allowed, i.e. Primary
keys must be NOT NULL
• Why?
– enables each row to be identified uniquely and
with certainty
Entity Integrity Example
Part:
Part#
P1
NULL
P3
P4
Description
Nut
Bolt
Tack
Nail
Q: Violates Howe’s rules as it stands?
Q: Could the NULL potentially be set to P1?
A: Possibly, therefore NULLs are never allowed in
primary keys.
Referential Integrity Rule
• Foreign key values must always be present in the
set of primary key values to which they are
associated, or be null.
ISSUES:
• How to deal with foreign key values when primary key
values are deleted or updated?
• How to deal with situations when trying to insert foreign
key values that are not in the primary key values?
– Restricted
– Nullify
– Cascaded
Referential Integrity Example
Part_Supplied:
Supplier#
S1
S2
S2
S2
S3
S3
Part#
P1
P1
P2
P3
P1
P3
Qty
25
10
22
35
10
65
Date
23/09/1999
24/09/1999
24/09/1999
24/09/1999
25/09/1999
26/09/1999
Part:
Part#
P1
P2
P3
P4
Description
Nut
Bolt
Tack
Nail
Referential Integrity Issues
Q: Delete P2 in Part – do we delete all rows relating to it
(cascade delete), or nullify the foreign key reference
(nullify), or not allow it (restricted delete)?
Q: Update P4 to P5 – do we update all rows relating to it
(cascade update), or not allow the update (restricted
update) or nullify those relating to it (nullify)?
Q: Insert a new Part_supplied with Part# = P6 – not allow
(restricted), or cascade to Part table (with null values
for the non-key attributes)?
Parent/Child (1:m)
• RESTRICT: Can’t delete parent rule of it has any
children
• CASCADE: If parent row is deleted then so are
all children. Parent deletions CASCADE to
children.
• NULLIFY: If parent row is deleted then all
children are automatically set to Null
• The default is normally RESTRICT
• Create Lecturer table, with foreign key DEPTNO from Dept
table.
Create Table Lecturer
(LectNo Char(2) NOT NULL,
LectName Char(20),
DeptNo char(2) NOT NULL,
Constraint LecPk primary key(LectNo),
Constraint LecFk foreign key (DeptNo) references Dept (DeptNo)
On Update Cascade);
This means that if the DeptNo is changed/updated in the Dept
table, then all of the appearances of DeptNo in the Lecturer
table will be similarly updated
Another example
Create Table Account (
AccNo number(6) not null,
Balance number (10,2),
Branchname CHAR(20),
Contraint AccountPK(AccNo),
constraint BankFK (Branchname) foreign key references Bank(Branchname)
on update cascade
on delete set null;
If a Bank changes its Branchname,
Also, if a bank is deleted
then that change will be
from the bank table, then
transmitted to all rows in the
all rows in the Account
account table with the equivalent value.
table with that branch name
will be set to null.
Download