Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke
The Relational Model
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke
Why Study the Relational Model?
 Most widely used model.
 Vendors: IBM, Informix, Microsoft, Oracle, Sybase,
etc.
 “Legacy systems” in older models
 E.G., IBM’s IMS
 Recent competitor: object-oriented model
 ObjectStore, Versant, Ontos
 A synthesis emerging: object-relational model
• Informix Universal Server, UniSQL, O2, Oracle, DB2
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke
Relational Database: Definitions
 Relational database: a set of relations
 Relation: made up of 2 parts:
 Instance : a table, with rows and columns.
#Rows = cardinality, #fields = degree / arity.
 Schema : specifies name of relation, plus name and
type of each column.
• E.G. Students(sid: string, name: string, login: string,
age: integer, gpa: real).
 Can think of a relation as a set of rows or
tuples (i.e., all rows are distinct).
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke
Example Instance of Students Relation
sid name login age gpa
53666 Jones jones@cs 18 3.4
53688 Smith smith@eecs 18 3.2
53650 Smith smith@math 19 3.8
 Cardinality = 3, degree = 5, all rows distinct
 Do all columns in a relation instance have to
be distinct?
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke
Relational Query Languages
 A major strength of the relational model:
supports simple, powerful querying of data.
 Queries can be written intuitively, and the
DBMS is responsible for efficient evaluation.
 The key: precise semantics for relational queries.
 Allows the optimizer to extensively re-order
operations, and still ensure that the answer does
not change.
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke
The SQL Query Language
 Developed by IBM (system R) in the 1970s
 Need for a standard since it is used by many
vendors
 Standards:
 SQL-86
 SQL-89 (minor revision)
 SQL-92 (major revision)
 SQL-99 (major extensions, current standard)
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke
The SQL Query Language
 To find all 18 year old students, we can write:
SELECT *
FROM Students S
WHERE S.age=18
•To find just names and logins, replace the first line:
SELECT S.name, S.login
sid name login age gpa
53666 Jones jones@cs 18 3.4
53688 Smith smith@ee 18 3.2
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke
Querying Multiple Relations
 What does the
following query
compute?
SELECT S.name, E.cid
FROM Students S, Enrolled E
WHERE S.sid=E.sid AND E.grade=“A”
S.name E.cid
Smith Topology112
sid cid grade
53831 Carnatic101 C
53831 Reggae203 B
53650 Topology112 A
53666 History105 B
Given the following instances
of Enrolled and Students:
we get:
sid name login age gpa
53666 Jones jones@cs 18 3.4
53688 Smith smith@eecs 18 3.2
53650 Smith smith@math 19 3.8
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke
Creating Relations in SQL
 Creates the Students
relation. Observe that the
type (domain) of each field
is specified, and enforced by
the DBMS whenever tuples
are added or modified.
 As another example, the
Enrolled table holds
information about courses
that students take.
CREATE TABLE Students
(sid: CHAR(20),
name: CHAR(20),
login: CHAR(10),
age: INTEGER,
gpa: REAL)
CREATE TABLE Enrolled
(sid: CHAR(20),
cid: CHAR(20),
grade: CHAR(2))
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke 1
Destroying and Altering Relations
 Destroys the relation Students. The schema
information and the tuples are deleted.
DROP TABLE Students
 The schema of Students is altered by adding a
new field; every tuple in the current instance
is extended with a null value in the new field.
ALTER TABLE Students
ADD COLUMN firstYear: integer
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke 1
Adding and Deleting Tuples
 Can insert a single tuple using:
INSERT INTO Students (sid, name, login, age, gpa)
VALUES (53688, ‘Smith’, ‘smith@ee’, 18, 3.2)
 Can delete all tuples satisfying some condition (e.g., name = Smith):
DELETE
FROM Students S
WHERE S.name = ‘Smith’
 Powerful variants of these commands are available; more later!
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke 1
Integrity Constraints (ICs)
 IC: condition that must be true for any 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, too!
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke 1
Primary Key Constraints
 A set of fields is a key for a relation if :
1. No two distinct tuples can have 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 (by DBA) to be the primary key.
 E.g., sid is a key for Students. (What about
name?) The set {sid, gpa} is a superkey.
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke 1
Instance of a Relation
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke 1
Primary Key, Candidate Key, Super
key
 sid
 sid, name
 name, age
 login, age
 sid, name, login, age, gpa
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke 1
Primary Key
CREATE TABLE Enrolled
(sid CHAR(20)
cid CHAR(20),
grade CHAR(2),
PRIMARY KEY (sid,cid) )
CREATE TABLE Enrolled
(sid CHAR(20)
cid CHAR(20),
grade CHAR(2),
PRIMARY KEY (sid),
UNIQUE (cid, grade) )
CREATE TABLE Students
(sid: CHAR(20) Primary key,
name: CHAR(20),
login: CHAR(10),
age: INTEGER,
gpa: REAL)
CREATE TABLE Enrolled
(sid: CHAR(20),
cid: CHAR(20),
grade: CHAR(2))
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke 1
Primary and Candidate Keys in SQL
 Possibly many candidate keys (specified using
UNIQUE), one of which is chosen as the primary key.
CREATE TABLE Enrolled
(sid CHAR(20)
cid CHAR(20),
grade CHAR(2),
PRIMARY KEY (sid,cid) )
 “For a given student and course,
there is a single grade.” vs.
“Students can take only one course,
and receive a single grade for that
course; further, no two students in a
course receive the same grade.”
 Used carelessly, an IC can prevent
the storage of database instances that
arise in practice!
CREATE TABLE Enrolled
(sid CHAR(20)
cid CHAR(20),
grade CHAR(2),
PRIMARY KEY (sid),
UNIQUE (cid, grade) )
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke 1
Foreign Keys, 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 is a foreign key referring to Students:
 Enrolled(sid: string, cid: string, grade: string)
 If all foreign key constraints are enforced, referential
integrity is achieved, i.e., no dangling references.
 Can you name a data model w/o referential integrity?
• Links in HTML!
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke 1
Foreign Keys in SQL
 Only students listed in the Students relation should
be allowed to enroll for courses.
CREATE TABLE Enrolled
(sid CHAR(20), cid CHAR(20), grade CHAR(2),
PRIMARY KEY (sid,cid),
FOREIGN KEY (sid) REFERENCES Students )
sid name login age gpa
53666 Jones jones@cs 18 3.4
53688 Smith smith@eecs 18 3.2
53650 Smith smith@math 19 3.8
sid cid grade
53666 Carnatic101 C
53666 Reggae203 B
53650 Topology112 A
53666 History105 B
Enrolled
Students
PK
FK
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke 2
Enforcing Referential Integrity
 Consider Students and Enrolled; sid in Enrolled is a
foreign key that references Students.
 What should be done if an Enrolled tuple with a
non-existent student id is inserted? (Reject it!)
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke 2
Enforcing Referential Integrity
 What should be done if a Students tuple is deleted?
 Also delete all Enrolled tuples that refer to it.
 Disallow deletion of a Students tuple that is referred to.
 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’.)
 Similar if primary key of Students tuple is updated.
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke 2
Foreign Keys
 there may well be some Students tuples that
are not referenced from Enrolled
 (e.g., the student with sid=50000).
 However, every studid value that appears in
the instance of the Enrolled table appears in
the primary key column of a row in the
Students table.
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke 2
Foreign Keys
try to insert the tuple (55555, Artl04, A) into E1,
the IC is violated because there is no tuple in 51
with sid 55555; the database system should reject
such an insertion.
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke 2
Foreign Keys
if we delete the tuple (53666, Jones, jones@cs, 18,
3.4) from 51, we violate the foreign key
constraint because the tuple (53666,Historyl05, B)
in El contains studid value 53666, the sid of the
deleted Students tuple.
The DBMS should disallow the deletion or,
perhaps, also delete the Enrolled tuple that refers
to the deleted Students tuple.
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke 2
Referential Integrity in SQL
 SQL/92 and SQL:1999
support all 4 options on
deletes and updates.
 Default is NO ACTION
(delete/update is rejected)
 CASCADE (also delete
all tuples that refer to
deleted tuple)
 SET NULL / SET DEFAULT
(sets foreign key value
of referencing tuple)
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 )
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke 2
Where do ICs Come From?
 ICs are based upon the semantics of the real-world
enterprise that is being described in the database
relations.
 We can check a database instance to see if an IC is
violated, but we can NEVER infer that an IC is true by
looking at an instance.
 An IC is a statement about all possible instances!
 From example, we know name is not a key, but the assertion
that sid is a key is given to us.
 Key and foreign key ICs are the most common; more
general ICs supported too.
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke 2
Logical DB Design: ER to Relational
 Entity sets to tables:
CREATE TABLE Employees
(ssn CHAR(11),
name CHAR(20),
lot INTEGER,
PRIMARY KEY (ssn))
Employees
ssn
name
lot
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke 2
Relationship
lot
dname
budget
did
since
name
Works_In Departments
Employees
ssn
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke 2
Relationship Sets to Tables
 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.
 All descriptive attributes.
CREATE TABLE Works_In(
ssn CHAR(11),
did INTEGER,
since DATE,
PRIMARY KEY (ssn, did),
FOREIGN KEY (ssn)
REFERENCES Employees,
FOREIGN KEY (did)
REFERENCES Departments)
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke 3
Relation with single entity set
CREATE TABLE Reports_To (
supervisor_ssn CHAR (11),
subordinate_ssn CHAR (11) ,
PRIMARY KEY (supervisor_ssn, subordinate_ssn),
FOREIGN KEY (supervisor_ssn) REFERENCES Employees(ssn),
FOREIGN KEY (subordinate_ssn) REFERENCES Employees(ssn) )
Reports_To
lot
name
Employees
supervisor
ssn
subordinate
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke 3
Review: Key Constraints
 Each dept has at
most one manager,
according to the
key constraint on
Manages.
Translation to
relational model?
Many-to-Many
1-to-1 1-to Many Many-to-1
dname
budget
did
since
lot
name
ssn
Manages
Employees Departments
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke 3
Key Constraint
 Key constraint on Manages
dname
budget
did
since
lot
name
ssn
Manages
Employees Departments
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke 3
Instance of Manages Relationship
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke 3
Translating ER Diagrams with Key Constraints
 Map relationship to a
table:
 Note that did is
the key now!
 Separate tables for
Employees and
Departments.
 Since each
department has a
unique manager, we
could instead
combine Manages
and Departments.
CREATE TABLE Manages(
ssn CHAR(11),
did INTEGER,
since DATE,
PRIMARY KEY (did),
FOREIGN KEY (ssn) REFERENCES Employees,
FOREIGN KEY (did) REFERENCES Departments)
CREATE TABLE Dept_Mgr(
did INTEGER,
dname CHAR(20),
budget REAL,
ssn CHAR(11),
since DATE,
PRIMARY KEY (did),
FOREIGN KEY (ssn) REFERENCES Employees)
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke 3
Review: Participation Constraints
 Does every department have a manager?
 If so, this is a participation constraint: the participation of
Departments in Manages is said to be total (vs. partial).
•Every did value in Departments table must appear in a
row of the Manages table (with a non-null ssn value!)
lot
name dname
budget
did
since
name dname
budget
did
since
Manages
since
Departments
Employees
ssn
Works_In
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke 3
Participation Constraint
lot
name dname
budget
did
since
name dname
budget
did
since
Manages
since
Departments
Employees
ssn
Works_In
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke 3
Instance
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke 3
Participation Constraints in SQL
 We can capture participation constraints involving
one entity set in a binary relationship, but little else
(without resorting to CHECK constraints).
CREATE TABLE Dept_Mgr(
did INTEGER,
dname CHAR(20),
budget REAL,
ssn CHAR(11) NOT NULL,
since DATE,
PRIMARY KEY (did),
FOREIGN KEY (ssn) REFERENCES Employees,
ON DELETE NO ACTION)
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke 3
Review: Weak Entities
 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 relationship set (1 owner, many weak entities).
 Weak entity set must have total participation in this
identifying relationship set.
lot
name
age
pname
Dependents
Employees
ssn
Policy
cost
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke 4
Translating Weak Entity Sets
 Weak entity set and identifying relationship
set are translated into a single table.
 When the owner entity is deleted, all owned weak
entities must also be deleted.
CREATE TABLE Dep_Policy (
pname CHAR(20),
age INTEGER,
cost REAL,
ssn CHAR(11) NOT NULL,
PRIMARY KEY (pname, ssn),
FOREIGN KEY (ssn) REFERENCES Employees,
ON DELETE CASCADE)
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke 4
Review: ISA Hierarchies
Contract_Emps
name
ssn
Employees
lot
hourly_wages
ISA
Hourly_Emps
contractid
hours_worked
 As in C++, or other PLs,
attributes are inherited.
 If we declare A ISA B, every A
entity is also considered to be a B
entity.
 Overlap constraints: Can Joe be an Hourly_Emps as well as
a Contract_Emps entity? (Allowed/disallowed)
 Covering constraints: Does every Employees entity also have
to be an Hourly_Emps or a Contract_Emps entity? (Yes/no)
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke 4
Hierarchies
Contract_Emps
name
ssn
Employees
lot
hourly_wages
ISA
Hourly_Emps
contractid
hours_worked
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke 4
Translating ISA Hierarchies to Relations
 General approach:
 3 relations: Employees, Hourly_Emps and Contract_Emps.
•Hourly_Emps: Every employee is recorded in
Employees. For hourly emps, extra info recorded in
Hourly_Emps (hourly_wages, hours_worked, ssn); must
delete Hourly_Emps tuple if referenced Employees
tuple is deleted).
•Queries involving all employees easy, those involving
just Hourly_Emps require a join to get some attributes.
 Alternative: Just Hourly_Emps and Contract_Emps.
 Hourly_Emps: ssn, name, lot, hourly_wages, hours_worked.
 Each employee must be in one of these two subclasses.
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke 4
Ternary Relation
CREATE TABLE Works_In2 ( ssn CHAR(11),
did INTEGER,
address CHAR(20) ,
since DATE,
PRIMARY KEY (ssn, did, address),
FOREIGN KEY (ssn) REFERENCES Employees,
FOREIGN KEY (address) REFERENCES Locations,
FOREIGN KEY (did) REFERENCES Departments)
lot
dname
budget
did
since
name
Works_In2 Departments
Employees
ssn
Location
address capacity
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke 4
Review: Binary vs. Ternary
Relationships
 What are the
additional
constraints in
the 2nd
diagram?
age
pname
Dependents
Covers
name
Employees
ssn lot
Policies
policyid cost
Beneficiary
age
pname
Dependents
policyid cost
Policies
Purchaser
name
Employees
ssn lot
Bad design
Better design
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke 4
Binary vs. Ternary Relationships (Contd.)
 The key
constraints allow
us to combine
Purchaser with
Policies and
Beneficiary with
Dependents.
 Participation
constraints lead to
NOT NULL
constraints.
 What if Policies is
a weak entity set?
CREATE TABLE Policies (
policyid INTEGER,
cost REAL,
ssn CHAR(11) NOT NULL,
PRIMARY KEY (policyid).
FOREIGN KEY (ssn) REFERENCES Employees,
ON DELETE CASCADE)
CREATE TABLE Dependents (
pname CHAR(20),
age INTEGER,
policyid INTEGER,
PRIMARY KEY (pname, policyid).
FOREIGN KEY (policyid) REFERENCES Policies,
ON DELETE CASCADE)
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke 4
Aggregation
budget
did
pid
started_on
pbudget
dname
until
Departments
Projects Sponsors
Employees
Monitors
lot
name
ssn
since
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke 4
Views
 A view is just a relation, but we store a
definition, rather than a set of tuples.
CREATE VIEW YoungActiveStudents (name, grade)
AS SELECT S.name, E.grade
FROM Students S, Enrolled E
WHERE S.sid = E.sid and S.age<21
 Views can be dropped using the DROP VIEW command.
 How to handle DROP TABLE if there’s a view on the table?
• DROP TABLE command has options to let the user specify
this.
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke 4
Student Table
CREATE TABLE Students ( sid CHAR(20) ,
name CHAR (30) ,
login CHAR(20) ,
age INTEGER,
gpa REAL,
UNIQUE (name, age),
CONSTRAINT StudentsKey PRIMARY KEY (sid) )
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke 5
Enrolled table
Enrolled(studid: string, cid: string, gTade: string)
CREATE TABLE Enrolled ( studid CHAR(20) ,
cid CHAR(20),
grade CHAR(10),
PRIMARY KEY (studid, cid),
FOREIGN KEY (studid) REFERENCES Students)
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke 5
Create View
CREATE VIEW B-Students (name, sid, course)
AS SELECT S.sname, S.sid, E.cid
FROM Students S, Enrolled E
WHERE S.sid = E.studid AND E.grade = 'B‘
CREATE VIEW GoodStudents (sid, gpa)
AS SELECT S.sid, S.gpa
FROM Students S
WHERE S.gpa> 3.0
name sid course
Jones 53666 History105
Guldu 53832 Reggae203
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke 5
Updates on Views
To insert a tuple (Dave, 50000, Reggae203) into B-Students
insert a tuple (Reggae203, B, 50000)
into Enrolled since there is already a tuple for sid 50000 in
Students.
To insert (John, 55000, Reggae203),
we have to insert (Reggae203, B, 55000)
into Enrolled and
also
insert (55000, John, null, null, null) into Students.
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke 5
CREATE VIEW ActiveStudents (name, login, club, since)
AS SELECT S.sname, S.login, C.cname, C.jyear
FROM Students S, Clubs C
WHERE S.sname = C.mname AND S.gpa> 3
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke 5
Updates on views
Club
Cname Joining
Year
sname
Painting 2018 Ram
Music 2019 Krish
Theatre 2020 Krish
Student
sid name login age gpa
500 Ram ram@cse 20 3.3
536 Sam sam@civil 19 3.4
538 Krish krish@ece 19 3.2
535 Krish krish@mech 20 3.8
ActiveStudents
name login club since
Ram ram@cse Painting 2018
Krish krish@ece Music 2019
Krish krish@ece Theatre 2020
Krish krish@mech Music 2019
Krish krish@mech Theatre 2020
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke 5
Updates on views
Club
Cname Joining
Year
sname
Painting 2018 Ram
Music 2019 Krish
Theatre 2020 Krish
Student
sid name login age gpa
500 Ram ram@cse 20 3.3
536 Sam sam@civil 19 3.4
538 Krish krish@ece 19 3.2
535 Krish krish@mech 20 3.8
ActiveStudents
name login club since
Ram ram@cse Painting 2018
Krish krish@ece Music 2019
Krish krish@ece Theatre 2020
Krish krish@mech Music 2019
Krish krish@mech Theatre 2020
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke 5
Updates on views
CREATE VIEW ActiveStudents (name, login, club, since)
AS SELECT S.sname, S.login, C.cname, C.jyear
FROM Students S, Clubs C
WHERE S.sname = C.mname AND S.gpa> 3
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke 5
Delete row from view
 delete the row (Smith, smith@ee, Hiking, 1997)
 ActiveStudents rows are not stored explicitly but computed as
needed from the Students and Clubs tablesusing the view
definition.
 change either Students or Clubs (or both) in such a way that
evaluating the view definition on the modified instance does
not produce the row (Smith, 8Tnith@ec, Hiking, 1997.)
 deleting the row (53688.. Smith, smith@ee, 18, 3.2) from Students
or deleting the row (Hiking, 1.997, Smith) from Clubs.
 Removing the Students row has the effect of also deleting the
row (Smith, smith@ee, Rowing, 1998) from the view
ActiveStudents.
 Removing the Clubs row has the effect of also deleting the row
(Smith, smith@math, Hiking, 1991) from the view ActiveStudents.
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke 5
Views and Security
 Views can be used to present necessary
information (or a summary), while hiding
details in underlying relation(s).
 Given YoungStudents, but not Students or
Enrolled, we can find students s who have are
enrolled, but not the cid’s of the courses they are
enrolled in.
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke 5
Relational Model: Summary
 A tabular representation of data.
 Simple and intuitive, currently the most widely used.
 Integrity constraints can be specified by the DBA,
based on application semantics. DBMS checks for
violations.
 Two important ICs: primary and foreign keys
 In addition, we always have domain constraints.
 Powerful and natural query languages exist.
 Rules to translate ER to relational model
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke 6
CASE STUDY: THE INTERNET SHOP
DBDudes Inc., a well-known database consulting firm, has been called in
to help Barns and Nobble (B&N) with its database design and
implementation.
B&N is a large bookstore specializing in books on horse racing, and it has
decided to go online.
DBDudes first verifies that B&N is willing and able to pay its steep fees
and then schedules a lunch meeting--billed to B&N, naturally to do
requirements analysis.
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke 6
CASE STUDY: THE INTERNET SHOP - Requirements Analysis
 The owner of B&N, unlike many people who need a database, has
thought extensively about what he wants and offers a concise
summary:
 "I would like my customers to be able to browse my catalog of books
and place orders over the Internet.
 Currently, I take orders over the phone.
 I have mostly corporate customers who call me and give me the ISBN
number of a book and a quantity;
 they often pay by credit card.
 I then prepare a shipment that contains the books they ordered.
 If I don't have enough copies in stock, I order additional copies and
delay the shipment until the new copies arrive;
 I want to ship a customer's entire order together.
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke 6
CASE STUDY: THE INTERNET SHOP - Requirements Analysis
 My catalog includes all the books I sell.
 For each book, the catalog contains its ISBN number, title, author,
 purcha.se price, sales price, and the year the book was published.
 Most of my Customers are regulars, and I have records with their
names and addresses.
 New customers have to call me first and establish an account before
they can use my website.
 On my new website, customers should first identify themselves by
their unique customer identification number.
 Then they should be able to browse my catalog and to place orders
online.
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke 6
ER – Internet Shop V1
Books Customers
Orders
title
author
isbn
qty
price
year_published
qty_in_
stock
cid
cname
address
cardnum Ship_
date
Order
_date
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke 6
Design Review – Internet Book Shop
Dude 2: What if a customer places two orders for the same book in one
day?
Dude 2: What if a customer places two orders for different books in one
day?
Dude 2: Ah, but what if a customer places two orders for the same book on
different days?
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke 6
Design Review – Internet Book Shop
 DBDudes has an internal design review at this point, and several
questions are raised. To protect their identities, we will refer to the
design team leader as Dude 1 and the design reviewer as Dude 2.
 Dude 2: What if a customer places two orders for the same book in one
day?
 Dude 1: The first order is handled by creating a new Orders
relationship and the second order is handled by updating the value of
the quantity attribute in this relationship.
 Dude 2: What if a customer places two orders for different books in one
day?
 Dude 1: No problem. Each instance of the Orders relationship set
relates the customer to a different book.
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke 6
Design Review – Internet Book Shop
 Dude 2: Ah, but what if a customer places two orders for the same book
on different days?
 Dude 1: We can use the attribute order date of the orders relationship to
distinguish the two orders.
 Dude 2: Oh no you can't. The attributes of Customers and Books must
jointly contain a key for Orders. So this design does not allow a
customer to place orders for the same book on different days.
 Dude 1: Yikes, you're right. Oh well, B&N probably won't care; we'll
see.
 DBDudes decides to proceed with the next phase, logical database
design
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke 6
Relation Data Model- Internet Shop V1
CREATE TABLE Books (
isbn CHAR ( 10) ,
title CHAR(80) ,
author CHAR(80),
qty_in-stock INTEGER,
price REAL,
yearpublished INTEGER)
CREATE TABLE Customers (
cid INTEGER,
cname CHAR(80),
address CHAR(200))
CREATE TABLE Orders ( isbn CHAR
(10) ,
cid INTEGER,
cardnum CHAR (16) ,
qty INTEGER,
order_date DATE,
ship_date DATE,
PRIMARY KEY (isbn, cid),
FOREIGN KEY (isbn) REFERENCES
Books,
FOREIGN KEY (cid) REFERENCES
Customers)
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke 6
Relation Data Model- Internet Shop V1
CREATE TABLE Orders ( isbn CHAR (10) ,
cid INTEGER,
cardnum CHAR (16) ,
qty INTEGER,
order_date DATE,
ship_date DATE,
PRIMARY KEY (isbn, cid),
FOREIGN KEY (isbn) REFERENCES Books,
FOREIGN KEY (cid) REFERENCES Customers)
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke 6
Relation Data Model- Internet Shop V2
The Orders table contains the field order_date and the key for the table
contains only the fields isbn and cid.
Because of this, a customer cannot order the same book On different days,
a restriction that was not intended. why not add the order-date attribute to
the key for the Orders table? This would eliminate the unwanted
restriction:
CREATE TABLE Orders ( isbn CHAR(10) ,
PRIMARY KEY (isbn, cid, order_date),
... )
Hack?
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke 7
Additional requirements – Internet Shop
 "Customers should be able to purchase several different books in a
single order. For example, if a customer wants to purchase three copies
of 'The English Teacher' and two copies of 'The Character of Physical
Law,' the customer should be able to place a single order for both
books."
 The design team leader, Dude 1, asks how this affects the shipping
policy. Does B&N still want to ship all books in an order together?
 The owner of B&N explains their shipping policy: "As soon as we have
enough copies of an ordered book we ship it, even if an order contains
several books. So it could happen that the three copies of 'The English
Teacher' are shipped today because we have five copies in stock, but
that 'The Character of Physical Law‘ is shipped tomorrow, because we
currently have only one copy in stock and another copy arrives
tomorrow.
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke 7
Additional requirements – Internet Shop
 In addition, my customers could place more than one order per day,
and they want to be able to identify the orders they placed."
 The DBDudes team thinks this over and identifies two new
requirements:
 First, it must be possible to order several different books in a single
order and
 second, a customer must be able to distinguish between several orders
placed the same day.
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke 7
Additional requirements – Internet Shop
 To accommodate these requirements, they introduce a new attribute
into the Orders table called ordernum, which uniquely identifies an
order and therefore the customer placing the order.
 However, since several books could be purchased in a single order,
ordernum and isbn are both needed to determine qty and ship_date in the
Orders table.
 Orders are assigned order numbers sequentially and orders that are
placed later have higher order numbers.
 If several orders are placed by the same customer on a single day, these
orders have different order numbers and can thus be distinguished.
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke 7
Relation Data Model- Internet Shop V3
 The SQL DDL statement to create the modified Orders table follows:
CREATE TABLE Orders (
ordernum INTEGER,
isbn CHAR(10),
cid INTEGER,
cardnum CHAR (16) ,
qty INTEGER,
ordeLdate DATE,
Ship_date DATE,
PRIMARY KEY (ordernum, isbn),
FOREIGN KEY (isbn) REFERENCES Books
FOREIGN KEY (cid) REFERENCES Customers)
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke 7
Relation Data Model- Internet Shop V3
 The owner of B&N is quite happy with this design for Orders, but has
realized something else. (DBDudes is not surprised; customers almost
always come up with several new requirements as the design
progresses.)
 While he wants all his employees to be able to look at the details of an
order, so that they can respond to customer enquiries, he wants
customers' credit card information to be secure.
 To address this concern, DBDudes creates the following view:
CREATE VIEW OrderInfo (isbn, cid, qty, order-date, ship_date)
AS SELECT O.cid, O.qty, O.orderdate, O.ship_date
FROM Orders O
 The plan is to allow employees to see this table, but not Orders; the
latter is restricted to B&N's Accounting division.

Ralational model, SQL query, key concept

  • 1.
    Database Management Systems3ed, R. Ramakrishnan and J. Gehrke The Relational Model
  • 2.
    Database Management Systems3ed, R. Ramakrishnan and J. Gehrke Why Study the Relational Model?  Most widely used model.  Vendors: IBM, Informix, Microsoft, Oracle, Sybase, etc.  “Legacy systems” in older models  E.G., IBM’s IMS  Recent competitor: object-oriented model  ObjectStore, Versant, Ontos  A synthesis emerging: object-relational model • Informix Universal Server, UniSQL, O2, Oracle, DB2
  • 3.
    Database Management Systems3ed, R. Ramakrishnan and J. Gehrke Relational Database: Definitions  Relational database: a set of relations  Relation: made up of 2 parts:  Instance : a table, with rows and columns. #Rows = cardinality, #fields = degree / arity.  Schema : specifies name of relation, plus name and type of each column. • E.G. Students(sid: string, name: string, login: string, age: integer, gpa: real).  Can think of a relation as a set of rows or tuples (i.e., all rows are distinct).
  • 4.
    Database Management Systems3ed, R. Ramakrishnan and J. Gehrke Example Instance of Students Relation sid name login age gpa 53666 Jones jones@cs 18 3.4 53688 Smith smith@eecs 18 3.2 53650 Smith smith@math 19 3.8  Cardinality = 3, degree = 5, all rows distinct  Do all columns in a relation instance have to be distinct?
  • 5.
    Database Management Systems3ed, R. Ramakrishnan and J. Gehrke Relational Query Languages  A major strength of the relational model: supports simple, powerful querying of data.  Queries can be written intuitively, and the DBMS is responsible for efficient evaluation.  The key: precise semantics for relational queries.  Allows the optimizer to extensively re-order operations, and still ensure that the answer does not change.
  • 6.
    Database Management Systems3ed, R. Ramakrishnan and J. Gehrke The SQL Query Language  Developed by IBM (system R) in the 1970s  Need for a standard since it is used by many vendors  Standards:  SQL-86  SQL-89 (minor revision)  SQL-92 (major revision)  SQL-99 (major extensions, current standard)
  • 7.
    Database Management Systems3ed, R. Ramakrishnan and J. Gehrke The SQL Query Language  To find all 18 year old students, we can write: SELECT * FROM Students S WHERE S.age=18 •To find just names and logins, replace the first line: SELECT S.name, S.login sid name login age gpa 53666 Jones jones@cs 18 3.4 53688 Smith smith@ee 18 3.2
  • 8.
    Database Management Systems3ed, R. Ramakrishnan and J. Gehrke Querying Multiple Relations  What does the following query compute? SELECT S.name, E.cid FROM Students S, Enrolled E WHERE S.sid=E.sid AND E.grade=“A” S.name E.cid Smith Topology112 sid cid grade 53831 Carnatic101 C 53831 Reggae203 B 53650 Topology112 A 53666 History105 B Given the following instances of Enrolled and Students: we get: sid name login age gpa 53666 Jones jones@cs 18 3.4 53688 Smith smith@eecs 18 3.2 53650 Smith smith@math 19 3.8
  • 9.
    Database Management Systems3ed, R. Ramakrishnan and J. Gehrke Creating Relations in SQL  Creates the Students relation. Observe that the type (domain) of each field is specified, and enforced by the DBMS whenever tuples are added or modified.  As another example, the Enrolled table holds information about courses that students take. CREATE TABLE Students (sid: CHAR(20), name: CHAR(20), login: CHAR(10), age: INTEGER, gpa: REAL) CREATE TABLE Enrolled (sid: CHAR(20), cid: CHAR(20), grade: CHAR(2))
  • 10.
    Database Management Systems3ed, R. Ramakrishnan and J. Gehrke 1 Destroying and Altering Relations  Destroys the relation Students. The schema information and the tuples are deleted. DROP TABLE Students  The schema of Students is altered by adding a new field; every tuple in the current instance is extended with a null value in the new field. ALTER TABLE Students ADD COLUMN firstYear: integer
  • 11.
    Database Management Systems3ed, R. Ramakrishnan and J. Gehrke 1 Adding and Deleting Tuples  Can insert a single tuple using: INSERT INTO Students (sid, name, login, age, gpa) VALUES (53688, ‘Smith’, ‘smith@ee’, 18, 3.2)  Can delete all tuples satisfying some condition (e.g., name = Smith): DELETE FROM Students S WHERE S.name = ‘Smith’  Powerful variants of these commands are available; more later!
  • 12.
    Database Management Systems3ed, R. Ramakrishnan and J. Gehrke 1 Integrity Constraints (ICs)  IC: condition that must be true for any 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, too!
  • 13.
    Database Management Systems3ed, R. Ramakrishnan and J. Gehrke 1 Primary Key Constraints  A set of fields is a key for a relation if : 1. No two distinct tuples can have 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 (by DBA) to be the primary key.  E.g., sid is a key for Students. (What about name?) The set {sid, gpa} is a superkey.
  • 14.
    Database Management Systems3ed, R. Ramakrishnan and J. Gehrke 1 Instance of a Relation
  • 15.
    Database Management Systems3ed, R. Ramakrishnan and J. Gehrke 1 Primary Key, Candidate Key, Super key  sid  sid, name  name, age  login, age  sid, name, login, age, gpa
  • 16.
    Database Management Systems3ed, R. Ramakrishnan and J. Gehrke 1 Primary Key CREATE TABLE Enrolled (sid CHAR(20) cid CHAR(20), grade CHAR(2), PRIMARY KEY (sid,cid) ) CREATE TABLE Enrolled (sid CHAR(20) cid CHAR(20), grade CHAR(2), PRIMARY KEY (sid), UNIQUE (cid, grade) ) CREATE TABLE Students (sid: CHAR(20) Primary key, name: CHAR(20), login: CHAR(10), age: INTEGER, gpa: REAL) CREATE TABLE Enrolled (sid: CHAR(20), cid: CHAR(20), grade: CHAR(2))
  • 17.
    Database Management Systems3ed, R. Ramakrishnan and J. Gehrke 1 Primary and Candidate Keys in SQL  Possibly many candidate keys (specified using UNIQUE), one of which is chosen as the primary key. CREATE TABLE Enrolled (sid CHAR(20) cid CHAR(20), grade CHAR(2), PRIMARY KEY (sid,cid) )  “For a given student and course, there is a single grade.” vs. “Students can take only one course, and receive a single grade for that course; further, no two students in a course receive the same grade.”  Used carelessly, an IC can prevent the storage of database instances that arise in practice! CREATE TABLE Enrolled (sid CHAR(20) cid CHAR(20), grade CHAR(2), PRIMARY KEY (sid), UNIQUE (cid, grade) )
  • 18.
    Database Management Systems3ed, R. Ramakrishnan and J. Gehrke 1 Foreign Keys, 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 is a foreign key referring to Students:  Enrolled(sid: string, cid: string, grade: string)  If all foreign key constraints are enforced, referential integrity is achieved, i.e., no dangling references.  Can you name a data model w/o referential integrity? • Links in HTML!
  • 19.
    Database Management Systems3ed, R. Ramakrishnan and J. Gehrke 1 Foreign Keys in SQL  Only students listed in the Students relation should be allowed to enroll for courses. CREATE TABLE Enrolled (sid CHAR(20), cid CHAR(20), grade CHAR(2), PRIMARY KEY (sid,cid), FOREIGN KEY (sid) REFERENCES Students ) sid name login age gpa 53666 Jones jones@cs 18 3.4 53688 Smith smith@eecs 18 3.2 53650 Smith smith@math 19 3.8 sid cid grade 53666 Carnatic101 C 53666 Reggae203 B 53650 Topology112 A 53666 History105 B Enrolled Students PK FK
  • 20.
    Database Management Systems3ed, R. Ramakrishnan and J. Gehrke 2 Enforcing Referential Integrity  Consider Students and Enrolled; sid in Enrolled is a foreign key that references Students.  What should be done if an Enrolled tuple with a non-existent student id is inserted? (Reject it!)
  • 21.
    Database Management Systems3ed, R. Ramakrishnan and J. Gehrke 2 Enforcing Referential Integrity  What should be done if a Students tuple is deleted?  Also delete all Enrolled tuples that refer to it.  Disallow deletion of a Students tuple that is referred to.  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’.)  Similar if primary key of Students tuple is updated.
  • 22.
    Database Management Systems3ed, R. Ramakrishnan and J. Gehrke 2 Foreign Keys  there may well be some Students tuples that are not referenced from Enrolled  (e.g., the student with sid=50000).  However, every studid value that appears in the instance of the Enrolled table appears in the primary key column of a row in the Students table.
  • 23.
    Database Management Systems3ed, R. Ramakrishnan and J. Gehrke 2 Foreign Keys try to insert the tuple (55555, Artl04, A) into E1, the IC is violated because there is no tuple in 51 with sid 55555; the database system should reject such an insertion.
  • 24.
    Database Management Systems3ed, R. Ramakrishnan and J. Gehrke 2 Foreign Keys if we delete the tuple (53666, Jones, jones@cs, 18, 3.4) from 51, we violate the foreign key constraint because the tuple (53666,Historyl05, B) in El contains studid value 53666, the sid of the deleted Students tuple. The DBMS should disallow the deletion or, perhaps, also delete the Enrolled tuple that refers to the deleted Students tuple.
  • 25.
    Database Management Systems3ed, R. Ramakrishnan and J. Gehrke 2 Referential Integrity in SQL  SQL/92 and SQL:1999 support all 4 options on deletes and updates.  Default is NO ACTION (delete/update is rejected)  CASCADE (also delete all tuples that refer to deleted tuple)  SET NULL / SET DEFAULT (sets foreign key value of referencing tuple) 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 )
  • 26.
    Database Management Systems3ed, R. Ramakrishnan and J. Gehrke 2 Where do ICs Come From?  ICs are based upon the semantics of the real-world enterprise that is being described in the database relations.  We can check a database instance to see if an IC is violated, but we can NEVER infer that an IC is true by looking at an instance.  An IC is a statement about all possible instances!  From example, we know name is not a key, but the assertion that sid is a key is given to us.  Key and foreign key ICs are the most common; more general ICs supported too.
  • 27.
    Database Management Systems3ed, R. Ramakrishnan and J. Gehrke 2 Logical DB Design: ER to Relational  Entity sets to tables: CREATE TABLE Employees (ssn CHAR(11), name CHAR(20), lot INTEGER, PRIMARY KEY (ssn)) Employees ssn name lot
  • 28.
    Database Management Systems3ed, R. Ramakrishnan and J. Gehrke 2 Relationship lot dname budget did since name Works_In Departments Employees ssn
  • 29.
    Database Management Systems3ed, R. Ramakrishnan and J. Gehrke 2 Relationship Sets to Tables  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.  All descriptive attributes. CREATE TABLE Works_In( ssn CHAR(11), did INTEGER, since DATE, PRIMARY KEY (ssn, did), FOREIGN KEY (ssn) REFERENCES Employees, FOREIGN KEY (did) REFERENCES Departments)
  • 30.
    Database Management Systems3ed, R. Ramakrishnan and J. Gehrke 3 Relation with single entity set CREATE TABLE Reports_To ( supervisor_ssn CHAR (11), subordinate_ssn CHAR (11) , PRIMARY KEY (supervisor_ssn, subordinate_ssn), FOREIGN KEY (supervisor_ssn) REFERENCES Employees(ssn), FOREIGN KEY (subordinate_ssn) REFERENCES Employees(ssn) ) Reports_To lot name Employees supervisor ssn subordinate
  • 31.
    Database Management Systems3ed, R. Ramakrishnan and J. Gehrke 3 Review: Key Constraints  Each dept has at most one manager, according to the key constraint on Manages. Translation to relational model? Many-to-Many 1-to-1 1-to Many Many-to-1 dname budget did since lot name ssn Manages Employees Departments
  • 32.
    Database Management Systems3ed, R. Ramakrishnan and J. Gehrke 3 Key Constraint  Key constraint on Manages dname budget did since lot name ssn Manages Employees Departments
  • 33.
    Database Management Systems3ed, R. Ramakrishnan and J. Gehrke 3 Instance of Manages Relationship
  • 34.
    Database Management Systems3ed, R. Ramakrishnan and J. Gehrke 3 Translating ER Diagrams with Key Constraints  Map relationship to a table:  Note that did is the key now!  Separate tables for Employees and Departments.  Since each department has a unique manager, we could instead combine Manages and Departments. CREATE TABLE Manages( ssn CHAR(11), did INTEGER, since DATE, PRIMARY KEY (did), FOREIGN KEY (ssn) REFERENCES Employees, FOREIGN KEY (did) REFERENCES Departments) CREATE TABLE Dept_Mgr( did INTEGER, dname CHAR(20), budget REAL, ssn CHAR(11), since DATE, PRIMARY KEY (did), FOREIGN KEY (ssn) REFERENCES Employees)
  • 35.
    Database Management Systems3ed, R. Ramakrishnan and J. Gehrke 3 Review: Participation Constraints  Does every department have a manager?  If so, this is a participation constraint: the participation of Departments in Manages is said to be total (vs. partial). •Every did value in Departments table must appear in a row of the Manages table (with a non-null ssn value!) lot name dname budget did since name dname budget did since Manages since Departments Employees ssn Works_In
  • 36.
    Database Management Systems3ed, R. Ramakrishnan and J. Gehrke 3 Participation Constraint lot name dname budget did since name dname budget did since Manages since Departments Employees ssn Works_In
  • 37.
    Database Management Systems3ed, R. Ramakrishnan and J. Gehrke 3 Instance
  • 38.
    Database Management Systems3ed, R. Ramakrishnan and J. Gehrke 3 Participation Constraints in SQL  We can capture participation constraints involving one entity set in a binary relationship, but little else (without resorting to CHECK constraints). CREATE TABLE Dept_Mgr( did INTEGER, dname CHAR(20), budget REAL, ssn CHAR(11) NOT NULL, since DATE, PRIMARY KEY (did), FOREIGN KEY (ssn) REFERENCES Employees, ON DELETE NO ACTION)
  • 39.
    Database Management Systems3ed, R. Ramakrishnan and J. Gehrke 3 Review: Weak Entities  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 relationship set (1 owner, many weak entities).  Weak entity set must have total participation in this identifying relationship set. lot name age pname Dependents Employees ssn Policy cost
  • 40.
    Database Management Systems3ed, R. Ramakrishnan and J. Gehrke 4 Translating Weak Entity Sets  Weak entity set and identifying relationship set are translated into a single table.  When the owner entity is deleted, all owned weak entities must also be deleted. CREATE TABLE Dep_Policy ( pname CHAR(20), age INTEGER, cost REAL, ssn CHAR(11) NOT NULL, PRIMARY KEY (pname, ssn), FOREIGN KEY (ssn) REFERENCES Employees, ON DELETE CASCADE)
  • 41.
    Database Management Systems3ed, R. Ramakrishnan and J. Gehrke 4 Review: ISA Hierarchies Contract_Emps name ssn Employees lot hourly_wages ISA Hourly_Emps contractid hours_worked  As in C++, or other PLs, attributes are inherited.  If we declare A ISA B, every A entity is also considered to be a B entity.  Overlap constraints: Can Joe be an Hourly_Emps as well as a Contract_Emps entity? (Allowed/disallowed)  Covering constraints: Does every Employees entity also have to be an Hourly_Emps or a Contract_Emps entity? (Yes/no)
  • 42.
    Database Management Systems3ed, R. Ramakrishnan and J. Gehrke 4 Hierarchies Contract_Emps name ssn Employees lot hourly_wages ISA Hourly_Emps contractid hours_worked
  • 43.
    Database Management Systems3ed, R. Ramakrishnan and J. Gehrke 4 Translating ISA Hierarchies to Relations  General approach:  3 relations: Employees, Hourly_Emps and Contract_Emps. •Hourly_Emps: Every employee is recorded in Employees. For hourly emps, extra info recorded in Hourly_Emps (hourly_wages, hours_worked, ssn); must delete Hourly_Emps tuple if referenced Employees tuple is deleted). •Queries involving all employees easy, those involving just Hourly_Emps require a join to get some attributes.  Alternative: Just Hourly_Emps and Contract_Emps.  Hourly_Emps: ssn, name, lot, hourly_wages, hours_worked.  Each employee must be in one of these two subclasses.
  • 44.
    Database Management Systems3ed, R. Ramakrishnan and J. Gehrke 4 Ternary Relation CREATE TABLE Works_In2 ( ssn CHAR(11), did INTEGER, address CHAR(20) , since DATE, PRIMARY KEY (ssn, did, address), FOREIGN KEY (ssn) REFERENCES Employees, FOREIGN KEY (address) REFERENCES Locations, FOREIGN KEY (did) REFERENCES Departments) lot dname budget did since name Works_In2 Departments Employees ssn Location address capacity
  • 45.
    Database Management Systems3ed, R. Ramakrishnan and J. Gehrke 4 Review: Binary vs. Ternary Relationships  What are the additional constraints in the 2nd diagram? age pname Dependents Covers name Employees ssn lot Policies policyid cost Beneficiary age pname Dependents policyid cost Policies Purchaser name Employees ssn lot Bad design Better design
  • 46.
    Database Management Systems3ed, R. Ramakrishnan and J. Gehrke 4 Binary vs. Ternary Relationships (Contd.)  The key constraints allow us to combine Purchaser with Policies and Beneficiary with Dependents.  Participation constraints lead to NOT NULL constraints.  What if Policies is a weak entity set? CREATE TABLE Policies ( policyid INTEGER, cost REAL, ssn CHAR(11) NOT NULL, PRIMARY KEY (policyid). FOREIGN KEY (ssn) REFERENCES Employees, ON DELETE CASCADE) CREATE TABLE Dependents ( pname CHAR(20), age INTEGER, policyid INTEGER, PRIMARY KEY (pname, policyid). FOREIGN KEY (policyid) REFERENCES Policies, ON DELETE CASCADE)
  • 47.
    Database Management Systems3ed, R. Ramakrishnan and J. Gehrke 4 Aggregation budget did pid started_on pbudget dname until Departments Projects Sponsors Employees Monitors lot name ssn since
  • 48.
    Database Management Systems3ed, R. Ramakrishnan and J. Gehrke 4 Views  A view is just a relation, but we store a definition, rather than a set of tuples. CREATE VIEW YoungActiveStudents (name, grade) AS SELECT S.name, E.grade FROM Students S, Enrolled E WHERE S.sid = E.sid and S.age<21  Views can be dropped using the DROP VIEW command.  How to handle DROP TABLE if there’s a view on the table? • DROP TABLE command has options to let the user specify this.
  • 49.
    Database Management Systems3ed, R. Ramakrishnan and J. Gehrke 4 Student Table CREATE TABLE Students ( sid CHAR(20) , name CHAR (30) , login CHAR(20) , age INTEGER, gpa REAL, UNIQUE (name, age), CONSTRAINT StudentsKey PRIMARY KEY (sid) )
  • 50.
    Database Management Systems3ed, R. Ramakrishnan and J. Gehrke 5 Enrolled table Enrolled(studid: string, cid: string, gTade: string) CREATE TABLE Enrolled ( studid CHAR(20) , cid CHAR(20), grade CHAR(10), PRIMARY KEY (studid, cid), FOREIGN KEY (studid) REFERENCES Students)
  • 51.
    Database Management Systems3ed, R. Ramakrishnan and J. Gehrke 5 Create View CREATE VIEW B-Students (name, sid, course) AS SELECT S.sname, S.sid, E.cid FROM Students S, Enrolled E WHERE S.sid = E.studid AND E.grade = 'B‘ CREATE VIEW GoodStudents (sid, gpa) AS SELECT S.sid, S.gpa FROM Students S WHERE S.gpa> 3.0 name sid course Jones 53666 History105 Guldu 53832 Reggae203
  • 52.
    Database Management Systems3ed, R. Ramakrishnan and J. Gehrke 5 Updates on Views To insert a tuple (Dave, 50000, Reggae203) into B-Students insert a tuple (Reggae203, B, 50000) into Enrolled since there is already a tuple for sid 50000 in Students. To insert (John, 55000, Reggae203), we have to insert (Reggae203, B, 55000) into Enrolled and also insert (55000, John, null, null, null) into Students.
  • 53.
    Database Management Systems3ed, R. Ramakrishnan and J. Gehrke 5 CREATE VIEW ActiveStudents (name, login, club, since) AS SELECT S.sname, S.login, C.cname, C.jyear FROM Students S, Clubs C WHERE S.sname = C.mname AND S.gpa> 3
  • 54.
    Database Management Systems3ed, R. Ramakrishnan and J. Gehrke 5 Updates on views Club Cname Joining Year sname Painting 2018 Ram Music 2019 Krish Theatre 2020 Krish Student sid name login age gpa 500 Ram ram@cse 20 3.3 536 Sam sam@civil 19 3.4 538 Krish krish@ece 19 3.2 535 Krish krish@mech 20 3.8 ActiveStudents name login club since Ram ram@cse Painting 2018 Krish krish@ece Music 2019 Krish krish@ece Theatre 2020 Krish krish@mech Music 2019 Krish krish@mech Theatre 2020
  • 55.
    Database Management Systems3ed, R. Ramakrishnan and J. Gehrke 5 Updates on views Club Cname Joining Year sname Painting 2018 Ram Music 2019 Krish Theatre 2020 Krish Student sid name login age gpa 500 Ram ram@cse 20 3.3 536 Sam sam@civil 19 3.4 538 Krish krish@ece 19 3.2 535 Krish krish@mech 20 3.8 ActiveStudents name login club since Ram ram@cse Painting 2018 Krish krish@ece Music 2019 Krish krish@ece Theatre 2020 Krish krish@mech Music 2019 Krish krish@mech Theatre 2020
  • 56.
    Database Management Systems3ed, R. Ramakrishnan and J. Gehrke 5 Updates on views CREATE VIEW ActiveStudents (name, login, club, since) AS SELECT S.sname, S.login, C.cname, C.jyear FROM Students S, Clubs C WHERE S.sname = C.mname AND S.gpa> 3
  • 57.
    Database Management Systems3ed, R. Ramakrishnan and J. Gehrke 5 Delete row from view  delete the row (Smith, smith@ee, Hiking, 1997)  ActiveStudents rows are not stored explicitly but computed as needed from the Students and Clubs tablesusing the view definition.  change either Students or Clubs (or both) in such a way that evaluating the view definition on the modified instance does not produce the row (Smith, 8Tnith@ec, Hiking, 1997.)  deleting the row (53688.. Smith, smith@ee, 18, 3.2) from Students or deleting the row (Hiking, 1.997, Smith) from Clubs.  Removing the Students row has the effect of also deleting the row (Smith, smith@ee, Rowing, 1998) from the view ActiveStudents.  Removing the Clubs row has the effect of also deleting the row (Smith, smith@math, Hiking, 1991) from the view ActiveStudents.
  • 58.
    Database Management Systems3ed, R. Ramakrishnan and J. Gehrke 5 Views and Security  Views can be used to present necessary information (or a summary), while hiding details in underlying relation(s).  Given YoungStudents, but not Students or Enrolled, we can find students s who have are enrolled, but not the cid’s of the courses they are enrolled in.
  • 59.
    Database Management Systems3ed, R. Ramakrishnan and J. Gehrke 5 Relational Model: Summary  A tabular representation of data.  Simple and intuitive, currently the most widely used.  Integrity constraints can be specified by the DBA, based on application semantics. DBMS checks for violations.  Two important ICs: primary and foreign keys  In addition, we always have domain constraints.  Powerful and natural query languages exist.  Rules to translate ER to relational model
  • 60.
    Database Management Systems3ed, R. Ramakrishnan and J. Gehrke 6 CASE STUDY: THE INTERNET SHOP DBDudes Inc., a well-known database consulting firm, has been called in to help Barns and Nobble (B&N) with its database design and implementation. B&N is a large bookstore specializing in books on horse racing, and it has decided to go online. DBDudes first verifies that B&N is willing and able to pay its steep fees and then schedules a lunch meeting--billed to B&N, naturally to do requirements analysis.
  • 61.
    Database Management Systems3ed, R. Ramakrishnan and J. Gehrke 6 CASE STUDY: THE INTERNET SHOP - Requirements Analysis  The owner of B&N, unlike many people who need a database, has thought extensively about what he wants and offers a concise summary:  "I would like my customers to be able to browse my catalog of books and place orders over the Internet.  Currently, I take orders over the phone.  I have mostly corporate customers who call me and give me the ISBN number of a book and a quantity;  they often pay by credit card.  I then prepare a shipment that contains the books they ordered.  If I don't have enough copies in stock, I order additional copies and delay the shipment until the new copies arrive;  I want to ship a customer's entire order together.
  • 62.
    Database Management Systems3ed, R. Ramakrishnan and J. Gehrke 6 CASE STUDY: THE INTERNET SHOP - Requirements Analysis  My catalog includes all the books I sell.  For each book, the catalog contains its ISBN number, title, author,  purcha.se price, sales price, and the year the book was published.  Most of my Customers are regulars, and I have records with their names and addresses.  New customers have to call me first and establish an account before they can use my website.  On my new website, customers should first identify themselves by their unique customer identification number.  Then they should be able to browse my catalog and to place orders online.
  • 63.
    Database Management Systems3ed, R. Ramakrishnan and J. Gehrke 6 ER – Internet Shop V1 Books Customers Orders title author isbn qty price year_published qty_in_ stock cid cname address cardnum Ship_ date Order _date
  • 64.
    Database Management Systems3ed, R. Ramakrishnan and J. Gehrke 6 Design Review – Internet Book Shop Dude 2: What if a customer places two orders for the same book in one day? Dude 2: What if a customer places two orders for different books in one day? Dude 2: Ah, but what if a customer places two orders for the same book on different days?
  • 65.
    Database Management Systems3ed, R. Ramakrishnan and J. Gehrke 6 Design Review – Internet Book Shop  DBDudes has an internal design review at this point, and several questions are raised. To protect their identities, we will refer to the design team leader as Dude 1 and the design reviewer as Dude 2.  Dude 2: What if a customer places two orders for the same book in one day?  Dude 1: The first order is handled by creating a new Orders relationship and the second order is handled by updating the value of the quantity attribute in this relationship.  Dude 2: What if a customer places two orders for different books in one day?  Dude 1: No problem. Each instance of the Orders relationship set relates the customer to a different book.
  • 66.
    Database Management Systems3ed, R. Ramakrishnan and J. Gehrke 6 Design Review – Internet Book Shop  Dude 2: Ah, but what if a customer places two orders for the same book on different days?  Dude 1: We can use the attribute order date of the orders relationship to distinguish the two orders.  Dude 2: Oh no you can't. The attributes of Customers and Books must jointly contain a key for Orders. So this design does not allow a customer to place orders for the same book on different days.  Dude 1: Yikes, you're right. Oh well, B&N probably won't care; we'll see.  DBDudes decides to proceed with the next phase, logical database design
  • 67.
    Database Management Systems3ed, R. Ramakrishnan and J. Gehrke 6 Relation Data Model- Internet Shop V1 CREATE TABLE Books ( isbn CHAR ( 10) , title CHAR(80) , author CHAR(80), qty_in-stock INTEGER, price REAL, yearpublished INTEGER) CREATE TABLE Customers ( cid INTEGER, cname CHAR(80), address CHAR(200)) CREATE TABLE Orders ( isbn CHAR (10) , cid INTEGER, cardnum CHAR (16) , qty INTEGER, order_date DATE, ship_date DATE, PRIMARY KEY (isbn, cid), FOREIGN KEY (isbn) REFERENCES Books, FOREIGN KEY (cid) REFERENCES Customers)
  • 68.
    Database Management Systems3ed, R. Ramakrishnan and J. Gehrke 6 Relation Data Model- Internet Shop V1 CREATE TABLE Orders ( isbn CHAR (10) , cid INTEGER, cardnum CHAR (16) , qty INTEGER, order_date DATE, ship_date DATE, PRIMARY KEY (isbn, cid), FOREIGN KEY (isbn) REFERENCES Books, FOREIGN KEY (cid) REFERENCES Customers)
  • 69.
    Database Management Systems3ed, R. Ramakrishnan and J. Gehrke 6 Relation Data Model- Internet Shop V2 The Orders table contains the field order_date and the key for the table contains only the fields isbn and cid. Because of this, a customer cannot order the same book On different days, a restriction that was not intended. why not add the order-date attribute to the key for the Orders table? This would eliminate the unwanted restriction: CREATE TABLE Orders ( isbn CHAR(10) , PRIMARY KEY (isbn, cid, order_date), ... ) Hack?
  • 70.
    Database Management Systems3ed, R. Ramakrishnan and J. Gehrke 7 Additional requirements – Internet Shop  "Customers should be able to purchase several different books in a single order. For example, if a customer wants to purchase three copies of 'The English Teacher' and two copies of 'The Character of Physical Law,' the customer should be able to place a single order for both books."  The design team leader, Dude 1, asks how this affects the shipping policy. Does B&N still want to ship all books in an order together?  The owner of B&N explains their shipping policy: "As soon as we have enough copies of an ordered book we ship it, even if an order contains several books. So it could happen that the three copies of 'The English Teacher' are shipped today because we have five copies in stock, but that 'The Character of Physical Law‘ is shipped tomorrow, because we currently have only one copy in stock and another copy arrives tomorrow.
  • 71.
    Database Management Systems3ed, R. Ramakrishnan and J. Gehrke 7 Additional requirements – Internet Shop  In addition, my customers could place more than one order per day, and they want to be able to identify the orders they placed."  The DBDudes team thinks this over and identifies two new requirements:  First, it must be possible to order several different books in a single order and  second, a customer must be able to distinguish between several orders placed the same day.
  • 72.
    Database Management Systems3ed, R. Ramakrishnan and J. Gehrke 7 Additional requirements – Internet Shop  To accommodate these requirements, they introduce a new attribute into the Orders table called ordernum, which uniquely identifies an order and therefore the customer placing the order.  However, since several books could be purchased in a single order, ordernum and isbn are both needed to determine qty and ship_date in the Orders table.  Orders are assigned order numbers sequentially and orders that are placed later have higher order numbers.  If several orders are placed by the same customer on a single day, these orders have different order numbers and can thus be distinguished.
  • 73.
    Database Management Systems3ed, R. Ramakrishnan and J. Gehrke 7 Relation Data Model- Internet Shop V3  The SQL DDL statement to create the modified Orders table follows: CREATE TABLE Orders ( ordernum INTEGER, isbn CHAR(10), cid INTEGER, cardnum CHAR (16) , qty INTEGER, ordeLdate DATE, Ship_date DATE, PRIMARY KEY (ordernum, isbn), FOREIGN KEY (isbn) REFERENCES Books FOREIGN KEY (cid) REFERENCES Customers)
  • 74.
    Database Management Systems3ed, R. Ramakrishnan and J. Gehrke 7 Relation Data Model- Internet Shop V3  The owner of B&N is quite happy with this design for Orders, but has realized something else. (DBDudes is not surprised; customers almost always come up with several new requirements as the design progresses.)  While he wants all his employees to be able to look at the details of an order, so that they can respond to customer enquiries, he wants customers' credit card information to be secure.  To address this concern, DBDudes creates the following view: CREATE VIEW OrderInfo (isbn, cid, qty, order-date, ship_date) AS SELECT O.cid, O.qty, O.orderdate, O.ship_date FROM Orders O  The plan is to allow employees to see this table, but not Orders; the latter is restricted to B&N's Accounting division.

Editor's Notes

  • #1 The slides for this text are organized into chapters. This lecture covers Chapter 3, and introduces the relational model of data. It covers the data model and integrity constraints in detail, together with the related SQL commands for creating tables and expressing these constraints. We discuss how to take an ER design and convert it to the schema for a relational database. Querying and modifying tables, and the concept of views, are covered briefly.
  • #27 The slides for this text are organized into several modules. Each lecture contains about enough material for a 1.25 hour class period. (The time estimate is very approximate--it will vary with the instructor, and lectures also differ in length; so use this as a rough guideline.) This covers Lectures 1 and 2 (of 6) in Module (5). Module (1): Introduction (DBMS, Relational Model) Module (2): Storage and File Organizations (Disks, Buffering, Indexes) Module (3): Database Concepts (Relational Queries, DDL/ICs, Views and Security) Module (4): Relational Implementation (Query Evaluation, Optimization) Module (5): Database Design (ER Model, Normalization, Physical Design, Tuning) Module (6): Transaction Processing (Concurrency Control, Recovery) Module (7): Advanced Topics