1.2.2 3A-IntegrityConstraints
1.2.2 3A-IntegrityConstraints
Integrity Constraints
Kathleen Durant
CS 3200
Lesson 3A
Outline for today
• Representing constraints from the ERM in the
Relational model
• Examples
2
Integrity Constraints
• Integrity Constraint (IC) is condition that must be
true for every instance of the database; e.g.,
domain constraints.
• ICs are specified when schema is defined.
• ICs are checked when relations are modified.
• A legal instance of a relation is one that satisfies
all specified ICs.
• DBMS should not allow illegal instances.
• If the DBMS checks ICs, stored data is more
faithful to real-world meaning.
• Avoids data entry errors 3
Key Constraints
• A set of fields is a key for a relation if :
1. No two distinct tuples can have the same values in all
key fields, and
2. This is not true for any subset of the key.
• Part 2 false? A superkey.
• If there’s >1 key for a relation, one of the keys is chosen to be the
primary key.
• E.g., sid is a key for Students.
• What about student name?
• The set {sid, gpa} is a superkey.
4
Specifying a primary key
• Primary key specified while creating a table
• CREATE TABLE Enrolled (sid CHAR(20), cid CHAR(40), grade
CHAR(2), PRIMARY KEY (sid, cid) )
5
Foreign Keys and Referential
Integrity
• Foreign key: Set of fields in one relation that is
used to `refer’ to a tuple in another relation.
• Must correspond to primary key of the second
relation.
• Like a `logical pointer’. E.g., sid in Enrolled is a foreign
key referring to Students:
• Enrolled(sid int, cid char(20), grade char(2))
• If all foreign key constraints are enforced, referential
integrity is achieved, i.e., no dangling references.
6
Foreign Keys
• Only students listed in the Students relation should be allowed to
enroll for courses.
• CREATE TABLE Enrolled (sid int, cid CHAR(20), grade CHAR(2),
PRIMARY KEY (sid, cid), FOREIGN KEY (sid) REFERENCES Students )
Enrolled
Students
SID Name Login DoB GPA Sid CId Grade
55515 Smith smith@ccs Jan 10,1990 3.82 55515 History 101 C
55516 Jones jones@hist Feb 11, 1992 2.98 55516 Biology 220 A
55517 Ali ali@math Sep 22, 1989 3.11 55517 Anthro 320 B
7
55518 Smith smith@math Nov 30, 1991 3.32 55518 Music 101 A
55518 Music 101 A
Enforcing Referential Integrity
• Consider Students and Enrolled tables:
• sid in Enrolled is a foreign key that references the Students table.
• What should be done if an Enrolled tuple with a nonexistent
student id is inserted?
• Reject it.
• What should be done if a Student,s tuple is deleted?
• You have choices
1. Also delete all Enrolled tuples that refer to it.
2. Disallow deletion of a Students tuple that is referred to.
3. Set sid in Enrolled tuples that refer to it to a default sid.
• (In SQL, also: Set sid in Enrolled tuples that refer to it to a special value null,
denoting `unknown’ or `inapplicable’.)
8
• Similar if primary key of Students tuple is updated.
Specifying behavior on Referential
Integrity violation
• Behavior specified at table create
• No action (Reject action that violates constraint)
• Update referring table (Update foreign key to the new value)
• Set to NULL (Set all foreign keys to a NULL)
• Set to a Default (Set all foreign keys to a default value)
• CREATE TABLE Enrolled (sid CHAR(20), cid CHAR(20), grade
CHAR(2), PRIMARY KEY (sid, cid), FOREIGN KEY (sid)
REFERENCES Students ON DELETE CASCADE ON UPDATE SET
DEFAULT )
9
Logical DB design: ER to Relational
• Translating an entity to a relation
Login
Sid
Dob Student Name
• Create table Student (sid int, Name char(20), Login(40), Dob date
primary key Sid )
• In translating a relationship set to a relation, attributes of the
relation must include:
• Keys for each participating entity set (as foreign keys).
• This set of attributes forms a superkey for the relation. 10
• All descriptive attributes.
Logical DB design: ER to
Relational • Create table
MajorCandidate (sid
Offers Dept. int, majorid int,
yearGrad int, PRIMARY
KEY (sid, majorid),
foreign key sid
REFERENCES Student
Make on delete cascade on
Major Course
up update cascade )
Declare Student
11
Total Participation Constraint
• CREATE TABLE
Offers Dept. CourseForMajor(
Mid INTEGER not
NULL, cid integer,
PRIMARY KEY (cid),
Required bool,
Make
Major Course FOREIGN KEY Mid,
up
ON DELETE NO
ACTION)
Declare Student
12
Total participation Constraint
• We can capture participation constraints for the
combined entity+relationship relation.
• Ensure foreign key value is not null
• E.g., ‘every Mid value in Major also appears in a
table Major
• Constraint is across tables
13
Weak Entity Constraint
Actor ID Birthdate Age
Scene
Number
Is in
Movie Actor
Role
Release
Director Title Name Photo
Date
• A weak entity can be identified uniquely only by considering the primary key
of another (owner) entity.
• Owner entity set and weak entity set must participate in a one to many 14
relationship set (1 owner, many weak entities).
• Weak entity set must have total participation in this identifying relationship
set.
Weak entity set
• Weak entity set and identifying relationship set are translated into a
single table.
Scene
Number
• When the owner entity (Movie) is deleted, all owned weak entities
(Scene) must also be deleted.
• CREATE TABLE MovieScene ( MovieName char(20) ReleaseDate
Date, SceneNumber int PRIMARY KEY (MovieName, ReleaseDate,
SceneNumber), FOREIGN KEY (MovieName, ReleaseDate)
REFERENCES Movies, ON DELETE CASCADE) 15
Translating ISA Relation
General approach:
Movie
• 4 relations: Movie, Action, Drama,
Comedy
• Every movie is recorded in Movie
ISA • For each genre extra information
is stored in the corresponding
table
Action Drama Comedy • Must delete genre tuple if
referenced movie tuple is deleted.
• Queries involving all movies: only
access Movies.
• Queries on genre tables require a
join to get some attributes.
Alternative: Just Genre tables
• Each movie must be in one of
16
these two subclasses.
View
• A view is just a relation, but we store a definition, rather than
a set of tuples.
• Views can be dropped using the DROP VIEW command.
17
From ER Model to Relational Model
• Build a table for each entity set
• Build a table for each relationship set if
necessary (more on this later)
• Make a column in the table for each attribute in
the entity set
• Indivisibility Rule and Ordering Rule
• Primary Key
18
Example – Strong Entity Set
SID Name SSN Name
Major Dept
GPA
20
Example – Weak Entity Set
Age
SID Name Name
Major GPA
22
Example – One-to-One Relationship Set
Degree
SID Name ID Code
Major GPA
25
Example – N-ary Relationship Set
P-Key1
D-Attribute A-Key
E-Set 1
P-Key3
E-Set 3
27
Representing Composite Attribute
• Relational Model Indivisibility Rule Applies
• One column for each component attribute
• NO column for the composite attribute itself
SSN Name
SSN Name Street City
9999 Dr. Smith 50 1st St. Fake
Professor
City
Major GPA
Stud_SID Children
1234 Johnson
1234 Mary
SID Name Major GPA
5678 Bart
1234 John CS 2.8
5678 Lisa 30
5678 Homer EE 3.6
5678 Maggie
Representing Class Hierarchy
• Two general approaches depending on
disjointness and completeness
• For non-disjoint and/or non-complete class hierarchy:
• create a table for each super class entity set according to normal
entity set translation method.
• Create a table for each subclass entity set with a column for each of
the attributes of that entity set plus one for each attributes of the
primary key of the super class entity set
• This primary key from super class entity set is also used as the
primary key for this new table
31
ISA Example SSN Name
Person
SID Status
Gender
ISA
Student
Major GPA
SSN Name Gender
1234 Homer Male
5678 Marge Female
33
Example SSN Name
No table created for
superclass entity set
NU people
ISA
SID
Student Faculty
Disjoint and
Complete mapping
Major GPA Dept
Dept
SID
Name
member
Primary Key of Advisor
Dept
36