0% found this document useful (0 votes)
36 views

The Relational Model: February 6, 2014

The document discusses the relational database model and related concepts. It begins with an overview of relational database design, including requirements analysis, conceptual design, logical design, schema refinement, and physical design. It then discusses why the relational model is widely studied and used in practice. The core concepts of the relational model such as relations, tuples, domains, keys, and integrity constraints are explained. Finally, the document covers relational query languages like SQL and how to define, manipulate, and enforce constraints on relational database schemas and instances.

Uploaded by

Maria Estrada
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
36 views

The Relational Model: February 6, 2014

The document discusses the relational database model and related concepts. It begins with an overview of relational database design, including requirements analysis, conceptual design, logical design, schema refinement, and physical design. It then discusses why the relational model is widely studied and used in practice. The core concepts of the relational model such as relations, tuples, domains, keys, and integrity constraints are explained. Finally, the document covers relational query languages like SQL and how to define, manipulate, and enforce constraints on relational database schemas and instances.

Uploaded by

Maria Estrada
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 43

The Relational Model!

"
February 6, 2014 "

Administrivia "
! Announcements"
-! PS 2 will be out this evening"

! Reading assignment"
-!

Chapter 3"

! Today"
-!

The Relational Model"

! Acknowledgement"
-! Some slide content courtesy of Ramakrishnan and Gehrke"

Designing a database "


1. Requirements analysis" -! What does the user want from the database?" 2. Conceptual DB design" -! High-level, semantic design, e.g., using ER Model" -! In sufcient detail to be converted into a data model" 3. Logical DB design" -! Convert conceptual design into a database schema in the data model of the chosen DBMS, e.g., relational data model" 4. Schema renement" -! Normalization (eliminating redundancy)" 5. Physical DB design" -! Workloads, performance indexing, clustering, etc." 6. Application and security design" -! Entities, roles of each entity, workow, security, etc.
3

Why study the relational model?"


! Most widely used model"
-!

Vendors: Oracle, IBM, Microsoft, etc."

! Legacy systems still in older models "


-!

e.g., IBMs IMS"

! Recent competitor: object-oriented model "


-! -!

ObjectStore, Versant, etc." A synthesis emerging: object-relational model!


! UniSQL, O2, Oracle, DB2, etc."

! Reality: OO or OR DBMS market collapsed"


-! Enterprise application companies (e.g., SAP) support their own Object to Relational Mapping on top of relational DB"
4

Relational model "


! Database model based on rst-order predicate logic" ! All data is represented as tuples, grouped into relations" ! Used to provide a declarative method for specifying data and queries; Users state:"
-! what information the database contains," -! what information they want from it, and" -! let the DBMS take care of how (describing data structures for storing the data and retrieval procedures for answering queries)."

! Implementations of the relational model use the SQL data denition and manipulation languages" ! A table in an SQL DB schema corresponds to a predicate variable; the contents of a table to a relation; constraints and queries correspond to predicates"
5

Relational model concepts "

Relational database "


! Relational database: a set of relations" ! Relation: consists of 2 parts:!
-!

Relation schema: species name of relation, plus name and domain of each column, e.g.,"
!

Students(sid: string, name: string, login: string, age: integer, gpa: real) "

-! Relation instance: a table (aka relation), with rows and columns"


! # of Rows = cardinality, # of elds = degree (or arity)"

! Can think of a relation as a set of rows or tuples (i.e., all rows are distinct) [not a bag of rows]"

Example instance of Students relation "


sid 666 688 650 name login Jones jones@cs Smith smith@eecs Smith smith@math age 18 18 19 gpa 3.4 3.9 3.8

! Cardinality = 3, degree = 5, all rows distinct" ! Do all columns in a relation instance have to be distinct?"

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 efcient 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"

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)" SQL-03 (collection of extensions to SQL-99, current standard)" SQL-06 (SQL and XML combination)" SQL-08 (minor revision on ORDER BY and a few more)"

10

The SQL query language "


! To nd everything about all 18 year old students, we can write:"
SELECT * FROM Students S WHERE S.age=18

sid

name

login jones@cs

age gpa 18 3.4 3.2

53666 Jones

53688 Smith smith@ee 18

! To nd just names and logins of all 18 year old students:"


SELECT S.name, FROM Students S WHERE S.age = 18

S.login

11

Querying multiple relations (next) "


What does this query" compute?" Given the following" instances of Enrolled " and Students:" SELECT S.name, E.cid FROM Students S, Enrolled E WHERE S.sid=E.sid AND E.grade=A

Enrolled
sid 53831 53831 53650 53666 cid grade Carnatic101 C Reggae203 B Topology112 A History105 B

Students sid name login 53666 Jones jones@cs 53688 Smith smith@eecs 53650 Smith smith@math

age 18 18 19

gpa 3.4 3.2 3.8

We get:"
S.name Smith E.cid Topology112
12

Creating relations in SQL "


! Creates the Students relation"
-! Observe that the type (domain) of each eld is specied, and enforced by the DBMS whenever tuples are added or modied " 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))

! As another example, the Enrolled table holds information about courses that students take"

13

Destroying and altering relations "


DROP TABLE

Students

! Destroys the relation Students"


-! The schema information and the tuples are deleted"

ALTER TABLE Students ADD COLUMN firstYear

integer

! The schema of Students is altered by adding a new eld" ! Every tuple in the current instance is extended with a null value in the new eld"
14

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!"


15

Integrity constraints (ICs) "


! IC: condition that must be true for any instance of the database; e.g., domain constraints!
-! -! -!

ICs are part of schema" ICs are specied when schema is dened" ICs are checked when relations are modied"

! A legal instance of a relation is one that satises all specied ICs"


-!

DBMS should not allow illegal instances"

! If the DBMS checks ICs, stored data is more faithful to realworld meaning"
-!

Avoid data entry errors, too!"


16

Primary key constraints "


! A set of elds is a candidate key (or simply key) for a relation if :"
1. No two distinct tuples can have same values in all key elds, and" 2. The condition 1 above is not true for any subset of the key." -! If it is true for any subset of the key, then it is a superkey." -! If theres more than one candidate key for a relation, one of the candidate 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" Every relation is guaranteed to have a key"
17

Primary and candidate keys in SQL "


! Possibly many candidate keys (specied using UNIQUE), one of which is chosen as the primary key" ! For a given student and course, there" CREATE TABLE Enrolled (sid CHAR(20) is a single grade. " cid CHAR(20), vs. " grade CHAR(2), PRIMARY KEY (sid,cid) ) Students can take only one course, " and receive a single grade for that" CREATE TABLE Enrolled course; further, no two students in a" (sid CHAR(20) cid CHAR(20), course receive the same grade." ! Used carelessly, an IC can prevent the storage of database instances that arise in practice!"
grade CHAR(2), PRIMARY KEY (sid), UNIQUE (cid, grade) )

18

Foreign keys, referential integrity "


! Foreign key: set of elds 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: string, cid: string, grade: string)" If all foreign key constraints are enforced, referential integrity is achieved, e.g., no dangling references" Can you name a data model without referential integrity? "
! Links in HTML!"

19

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 )

Enrolled
sid 53666 53666 53650 53666

cid grade Carnatic101 C Reggae203 B Topology112 A History105 B

sid 53666 53688 53650

Students

name login Jones jones@cs Smith smith@eecs Smith smith@math

age 18 18 19

gpa 3.4 3.2 3.8


20

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!)" ! 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 by another, " Set sid in Enrolled tuples that refer to it to a default sid, or" (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"


21

Referential integrity in SQL "


! SQL supports 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 )

22

Transactions and constraints "


! Checking constraints at what granularity?"
-! Statement" -! Transaction"
"

! Statement level would be too inexible"


-! SQL allows a constraint to be in DEFERRED or IMMEDIATE mode"

! Think about what a DBMS would have to do to make this work!"

23

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"

24

General constraints "


! Domain, key, foreign constraints are considered to be a fundamental part of relational data model" ! Other more general constraints are supported too:"
-! Table constraints"
! Associated with a single table" ! Checked whenever the table is modied"

-! Assertions"
! Involve multiple tables" ! Checked whenever any of the tables is modied"

25

Logical DB Design: ER to Relational "

26

Designing a database "


1. Requirements analysis" -! What does the user want from the database?" 2. Conceptual DB design" -! High-level, semantic design, e.g., using ER Model" -! In sufcient detail to be converted into a data model" 3. Logical DB design" -! Convert conceptual design into a database schema in the data model of the chosen DBMS, e.g., relational data model" 4. Schema renement" -! Normalization (eliminating redundancy)" 5. Physical DB design" -! Workloads, performance indexing, clustering, etc." 6. Application and security design" -! Entities, roles of each entity, workow, security, etc.
27

Entity sets to tables


name

ssn

lot CREATE TABLE Employees ( ssn CHAR(11), name CHAR(20), lot INTEGER, PRIMARY KEY (ssn)) - Domain of each attribute - Primary key
28

Employees

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) NOT NULL, did INTEGER, since DATE, PRIMARY KEY (ssn, did), FOREIGN KEY (ssn) REFERENCES Employees, FOREIGN KEY (did) REFERENCES Departments)

29

Review: Key constraints


since

! Each dept has at most one manager, according to the key constraint on Manages

name ssn lot did

dname budget

Employees

Manages

Departments

Translation to relational model?


1:1 1:n n:1 n:n
30

Translating ER diagrams with key constraints


! Map relationship to a table:
-!

-!

Note that did is the key! Not did and ssn together since each dept has at most one manager Separate tables for Employees 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)

! Since each department has a unique manager, we could instead combine Manages and Departments into one

31

Review: Participation constraints "


! A department has at most one manager (key constraint, arrow)" ! Does every department have a manager then?"
-!

If so, this is a participation constraint"


! ! !

The participation of Departments in Manages is said to be total. (cf. partial)" Participation of an entity set in a relationship set" Every did value in Departments must appear in a row of the Manages table (with a non-null ssn value!)" since lot did Manages

name ssn Employees

dname budget Departments

WorksIn

since

WorksIn: Thick: total" -! Each employee works in at least one dept" -! Each dept has at least one employee"
32

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) What would CASCADE mean if we used it instead of NO ACTION?

33

Review: Weak entity sets "


! What if an entity set does not have a key?" ! A weak entity can be identied uniquely only by considering the primary key of another (owner) entity"
-! -! -!

Owner entity set and weak entity set must participate in a 1-to-many relationship set (1 owner, 1+ weak entities)" Weak entity set must have total participation in this identifying relationship set" Primary key plus partial key together can uniquely identify a weak entity, e.g., ssn and pname together below" name

ssn

lot

cost

pname

age

Employees

Policy

Dependents

- Dependents is a weak entity set" -! Policy is its identifying relationship set" -! Employees is its identifying owner"

34

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)

Is NOT NULL necessary?


35

Review: ISA hierarchies "


name

! As in Java, attributes are inherited" ! If we declare A ISA B, every A entity is also considered to be a B entity"
-! Overlap constraints: Can Jim be an HourlyEmps as well as a ContractEmps entity? (allowed/disallowed)" -! Covering constraints: Does every Employees entity also have to be an HourlyEmps or a ContractEmps entity? (yes/no) ! -! Reasons for using ISA:"
! To add descriptive attributes specic to a subclass" ! To identify entities that participate in a relationship"

ssn

lot

Employees

hours_worked

ISA

HourlyEmps

ContractEmps

hourly_wages

contractid

36

Translating ISA hierarchies to relations


! General approach:
-!

3 relations: Employees, HourlyEmps and ContractEmps


! Every employee is recorded in Employees. For hourly emps, extra info recorded in HourlyEmps (hourlyWages, hoursWorked, ssn); must delete HourlyEmps tuple if referenced Employees tuple is deleted). ! Queries involving all employees easy; those involving just HourlyEmps require a join to get the remaining attributes of Employees.

! Alternative: Just HourlyEmps and ContractEmps


-! -! -!

HourlyEmps: ssn, name, lot, hourlyWages, hoursWorked Each employee must be in one of these two subclasses No way to represent employees who are neither hourly employees nor contract employees

37

Review: Binary vs. ternary relationships


ssn name lot Covers Policies policyid ssn name lot cost pname age pname age

Employees

Dependents

Employees Purchaser Beneficiary

Dependents

Policies policyid cost


38

Binary vs. ternary relationships (cont.)


! Binary: the key constraints allow us to combine Purchaser with Policies and Beneficiary with Dependents ! Participation constraints lead to
NOT NULL
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 NOT NULL, PRIMARY KEY (pname, policyid). FOREIGN KEY (policyid) REFERENCES Policies, ON DELETE CASCADE) CREATE TABLE Employees ( . . .)
39

constraints

Views
! A view is a relation: we store a definition, and compute the tuples when needed
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

! Some views may be updated ! Views can be dropped using the DROP VIEW command
-!

How to handle DROP TABLE if theres a view on the table?


!

DROP TABLE command has options (RESTRICT or CASCADE) to let the user specify this
40

Views and security


! Views can be used to present necessary information (or a summary), while hiding details in underlying relation(s)
-!

Given YoungActiveStudents, but not Students or Enrolled, we can find students who are enrolled, but not the cids of the courses they are enrolled in

41

Summary: relational model


! 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 ! Views as external schema

42

Next . . .
Chapter 4 Relational Algebra

43

You might also like