Relational Algebra

Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 55

RELATIONAL MODEL

Relational Database: Definitions

• Relational database: a set of relations

• Relation: made up of 2 ways:


– 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).
• Relation is a set of rows or tuples (i.e., all rows are distinct).

Slide No:L1-1
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?
Slide No:L1-2
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.

Slide No:L1-3
The SQL Query Language

SELECT *
FROM Students S WHERE S.age=18

sid name login age gpa


53666 Jones jones@cs 18 3.4
53688 Smith smith@ee 18 3.2

Slide No:L1-4
Querying Multiple Relations

• What does the following SELECT S.name, E.cid


query compute? FROM Students S, Enrolled E
WHERE S.sid=E.sid AND E.grade=“A”

Given the following instances sid cid grade


of Enrolled and Students: 53831 Carnatic101 C
sid name login age gpa 53831 Reggae203 B
53650 Topology112 A
53666 Jones jones@cs 18 3.4 53666 History105 B
53688 Smith smith@eecs 18 3.2
53650 Smith smith@math 19 3.8
S.name E.cid
we get: Smith Topology112

Slide No:L1-5
Creating Relations in SQL

• Creates the Students CREATE TABLE Students


relation. Observe that the (sid: CHAR(20),
type of each field is name: CHAR(20),
specified, and enforced by login: CHAR(10),
the DBMS whenever age: INTEGER,
tuples are added or gpa: REAL)
modified.
• As another example, the CREATE TABLE Enrolled
Enrolled table holds (sid: CHAR(20),
information about courses cid: CHAR(20),
that students take. grade: CHAR(2))

Slide No:L1-6
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 field; every tuple in the current instance is
extended with a null value in the new field.

Slide No:L1-7
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’

Slide No:L1-8
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!

Slide No:L1-9
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.

Slide No:L1-10
Primary and Candidate Keys in SQL

• Possibly many candidate keys (specified using UNIQUE), one of which is


chosen as the primary key.

 “For a given student and course, CREATE TABLE Enrolled


there is a single grade.” vs. (sid CHAR(20)
“Students can take only one cid CHAR(20),
course, and receive a single grade grade CHAR(2),
for that course; further, no two PRIMARY KEY (sid,cid) )
students in a course receive the
same grade.” CREATE TABLE Enrolled
 Used carelessly, an IC can (sid CHAR(20)
prevent the storage of database cid CHAR(20),
instances that arise in practice! grade CHAR(2),
PRIMARY KEY (sid),
UNIQUE (cid, grade) )
Slide No:L1-11
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!

Slide No:L1-12
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 cid grade Students
sid name login age gpa
53666 Carnatic101 C
53666 Reggae203 B 53666 Jones jones@cs 18 3.4
53650 Topology112 A 53688 Smith smith@eecs 18 3.2
53666 History105 B 53650 Smith smith@math 19 3.8

Slide No:L1-13
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.
– 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.

Slide No:L2-1
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) CREATE TABLE Enrolled
– CASCADE (also delete all (sid CHAR(20),
tuples that refer to deleted cid CHAR(20),
tuple)
– SET NULL / SET DEFAULT
grade CHAR(2),
(sets foreign key value of PRIMARY KEY (sid,cid),
referencing tuple) FOREIGN KEY (sid)
REFERENCES Students
ON DELETE CASCADE
ON UPDATE SET
DEFAULT )

Slide No:L2-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.

Slide No:L2-3
Logical DB Design: ER to Relational

• Entity sets to tables:

CREATE TABLE Employees


name (ssn CHAR(11),
ssn lot name CHAR(20),
lot INTEGER,
Employees PRIMARY KEY (ssn))

Slide No:L3-1
Relationship Sets to Tables

• In translating a relationship set to


a relation, attributes of the
relation must include: CREATE TABLE Works_In(
– Keys for each participating ssn CHAR(11),
entity set (as foreign keys). did INTEGER,
• This set of attributes since DATE,
forms a superkey for the
PRIMARY KEY (ssn, did),
relation.
– All descriptive attributes. FOREIGN KEY (ssn)
REFERENCES Employees,
FOREIGN KEY (did)
REFERENCES Departments)

Slide No:L3-2
Review: Key Constraints

• Each dept has at most


one manager, according
to the key constraint since
on Manages. name dname
ssn lot did budget

Employees Manages Departments

Translation to
relational model?

1-to-1 1-to Many Many-to-1 Many-to-Many


Slide No:L3-3
Translating ER Diagrams with Key
Constraints
• Map relationship to a
table: CREATE TABLE Manages(
– Note that did is the ssn CHAR(11),
key now! did INTEGER,
– Separate tables for since DATE,
Employees and PRIMARY KEY (did),
Departments. FOREIGN KEY (ssn) REFERENCES Employees,
• Since each department FOREIGN KEY (did) REFERENCES Departments)
has a unique manager,
we could instead combine
Manages and CREATE TABLE Dept_Mgr(
Departments. did INTEGER,
dname CHAR(20),
budget REAL,
ssn CHAR(11),
since DATE,
PRIMARY KEY (did),
FOREIGN KEY (ssn) REFERENCES Employees)

Slide No:L3-4
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!)

since
name dname
ssn lot did budget

Employees Manages Departments

Works_In

since

Slide No:L3-5
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)

Slide No:L3-6
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.

name
cost pname age
ssn lot

Employees Policy Dependents

Slide No:L4-1
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)

Slide No:L4-2
Review: ISA Hierarchies

name
 As in C++, or other ssn lot
PLs, attributes are
inherited. Employees

 If we declare A ISA B,
hourly_wages hours_worked
every A entity is also ISA
contractid
considered to be a B
entity. Contract_Emps
Hourly_Emps

• 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)

Slide No:L4-3
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.

Slide No:L4-4
Review: Binary vs. Ternary Relationships
name
ssn lot pname age
• What are the
additional Employees Covers
constraints in the
Dependents
2nd diagram? Bad design Policies

policyid cost

name pname age


ssn lot
Dependents
Employees

Purchaser
Beneficiary

Better design Policies

Slide No:L4-5
policyid cost
Binary vs. Ternary Relationships (Contd.)
CREATE TABLE Policies (
• The key
constraints allow policyid INTEGER,
us to combine cost REAL,
Purchaser with ssn CHAR(11) NOT NULL,
Policies and PRIMARY KEY (policyid).
Beneficiary with FOREIGN KEY (ssn) REFERENCES Employees,
Dependents. ON DELETE CASCADE)
• Participation CREATE TABLE Dependents (
constraints lead pname CHAR(20),
to NOT NULL
age INTEGER,
constraints.
policyid INTEGER,
• What if Policies
PRIMARY KEY (pname, policyid).
is a weak entity
set? FOREIGN KEY (policyid) REFERENCES Policies,
ON DELETE CASCADE)
Slide No:L4-6
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.

Slide No:L5-1
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.

Slide No:L5-2
View Definition
• A relation that is not of the conceptual model but is
made visible to a user as a “virtual relation” is called
a view.
• A view is defined using the create view statement
which has the form

create view v as < query expression >


where <query expression> is any legal SQL
expression. The view name is represented by v.
• Once a view is defined, the view name can be used to
refer to the virtual relation that the view generates.

Slide No:L5-3
Example Queries
• A view consisting of branches and their customers
create view all_customer as
(select branch_name, customer_name
from depositor, account
where depositor.account_number =
account.account_number )
union
(select branch_name, customer_name
from borrower, loan
where borrower.loan_number =
loan.loan_number )
 Find all customers of the Perryridge branch

select customer_name
from all_customer
where branch_name = 'Perryridge'

Slide No:L5-4
Uses of Views
• Hiding some information from some users
– Consider a user who needs to know a customer’s name,
loan number and branch name, but has no need to see the
loan amount.
– Define a view
(create view cust_loan_data as
select customer_name, borrower.loan_number,
branch_name
from borrower, loan
where borrower.loan_number = loan.loan_number )
– Grant the user permission to read cust_loan_data, but not
borrower or loan
• Predefined queries to make writing of other queries
easier
– Common example: Aggregate queries used for statistical
analysis of data

Slide No:L5-5
Processing of Views
• When a view is created
– the query expression is stored in the database along with the
view name
– the expression is substituted into any query using the view
• Views definitions containing views
– One view may be used in the expression defining another view
– A view relation v1 is said to depend directly on a view relation
v2 if v2 is used in the expression defining v1
– A view relation v1 is said to depend on view relation v2 if either
v1 depends directly to v2 or there is a path of dependencies
from v1 to v2
– A view relation v is said to be recursive if it depends on itself.

Slide No:L5-6
View Expansion
• A way to define the meaning of views defined in terms of
other views.
• Let view v1 be defined by an expression e1 that may itself
contain uses of view relations.
• View expansion of an expression repeats the following
replacement step:
repeat
Find any view relation vi in e1
Replace the view relation vi by the expression defining
vi
until no more view relations are present in e1
• As long as the view definitions are not recursive, this loop will
terminate

Slide No:L5-7
With Clause
• The with clause provides a way of defining a
temporary view whose definition is available only to
the query in which the with clause occurs.
• Find all accounts with the maximum balance

with max_balance (value) as


select max (balance)
from account
select account_number
from account, max_balance
where account.balance = max_balance.value

Slide No:L5-8
Complex Queries using With Clause
• Find all branches where the total account deposit is greater
than the average of the total account deposits at all branches.

with branch_total (branch_name, value) as


select branch_name, sum (balance)
from account
group by branch_name
with branch_total_avg (value) as
select avg (value)
from branch_total
select branch_name
from branch_total, branch_total_avg
where branch_total.value >= branch_total_avg.value

• Note: the exact syntax supported by your database may


vary slightly.
– E.g. Oracle syntax is of the form
with branch_total as ( select .. ),
branch_total_avg as ( select .. )
select … Slide No:L5-9
Update of a View
• Create a view of all loan data in the loan relation,
hiding the amount attribute
create view loan_branch as
select loan_number, branch_name
from loan
• Add a new tuple to loan_branch
insert into loan_branch
values ('L-37‘, 'Perryridge‘)
This insertion must be represented by the insertion
of the tuple
('L-37', 'Perryridge', null )
into the loan relation

Slide No:L5-10
Formal Relational Query Languages

• Two mathematical Query Languages form the


basis for “real” languages (e.g. SQL), and for
implementation:
– Relational Algebra: More operational, very useful for
representing execution plans.
– Relational Calculus: Lets users describe what they
want, rather than how to compute it. (Non-
operational, declarative.)

Slide No:L6-1
Example Instances
R1 sid bid day
22 101 10/10/96
58 103 11/12/96
• “Sailors” and “Reserves”
relations for our examples. sid sname rating age
• We’ll use positional or S1
named field notation, 22 dustin 7 45.0
assume that names of
fields in query results are 31 lubber 8 55.5
`inherited’ from names of 58 rusty 10 35.0
fields in query input
relations. sid sname rating age
S2
28 yuppy 9 35.0
31 lubber 8 55.5
44 guppy 5 35.0
58 rusty 10 35.0
Slide No:L6-3
Relational Algebra

• Basic operations:
– Selection ( ) Selects a subset of rows from relation.
– Projection ( ) Deletes unwanted columns from relation.
– Cross-product (  ) Allows us to combine two relations.
– Set-difference ( __ ) Tuples in reln. 1, but not in reln. 2.
– Union (  ) Tuples in reln. 1 and in reln. 2.
• Additional operations:
– Intersection, join, division, renaming: Not essential, but (very!)
useful.
• Since each operation returns a relation, operations can be composed!
(Algebra is “closed”.)

Slide No:L6-4
Projection

• Deletes attributes that are not


in projection list.
• Schema of result contains
exactly the fields in the
projection list, with the same
names that they had in the
(only) input relation.
• Projection operator has to
eliminate duplicates! (Why??) age
– Note: real systems typically 35.0
don’t do duplicate elimination
unless the user explicitly asks 55.5
 age(S2)
for it. (Why not?)

Slide No:L6-5
Selection
sid sname rating age
• Selects rows that satisfy 28 yuppy 9 35.0
selection condition. 58 rusty 10 35.0
• No duplicates in result!
(Why?)  rating 8(S2)
• Schema of result identical to
schema of (only) input
relation. sname rating
• Result relation can be the
input for another relational
yuppy 9
algebra operation! (Operator rusty 10
composition.)

 sname,rating ( rating 8(S 2))

Slide No:L6-6
Union, Intersection, Set-Difference
• All of these operations take two sid sname rating age
input relations, which must be
union-compatible: 22 dustin 7 45.0
– Same number of fields.
31 lubber 8 55.5
– `Corresponding’ fields have
the same type.
58 rusty 10 35.0
• What is the schema of result? 44 guppy 5 35.0
28 yuppy 9 35.0

S1 S2
sid sname rating age sid sname rating age
22 dustin 7 45.0 31 lubber 8 55.5
58 rusty 10 35.0
S1 S2
S1 S2
Slide No:L6-7
Cross-Product
• Each row of S1 is paired with each row of R1.
• Result schema has one field per field of S1 and R1,
with field names `inherited’ if possible.
– Conflict: Both S1 and R1 have a field called sid.

(sid) sname rating age (sid) bid day


22 dustin 7 45.0 22 101 10/10/96
22 dustin 7 45.0 58 103 11/12/96
31 lubber 8 55.5 22 101 10/10/96
31 lubber 8 55.5 58 103 11/12/96
58 rusty 10 35.0 22 101 10/10/96
58 rusty 10 35.0 58 103 11/12/96

 Renaming operator:  (C(1 sid1, 5  sid 2), S1 R1)

Slide No:L6-8
Joins

R  c S   c ( R  S)
• Condition Join:
(sid) sname rating age (sid) bid day
22 dustin 7 45.0 58 103 11/12/96
31 lubber 8 55.5 58 103 11/12/96
S1  R1
S1. sid  R1. sid

• Result schema same as that of cross-product.


• Fewer tuples than cross-product, might be able
to compute more efficiently
• Sometimes called a theta-join.

Slide No:L6-9
Joins

• Equi-Join: A special case of condition join where the


condition c contains only equalities.
sid sname rating age bid day
22 dustin 7 45.0 101 10/10/96
58 rusty 10 35.0 103 11/12/96

S1  R1
sid
• Result schema similar to cross-product, but only one
copy of fields for which equality is specified.
• Natural Join: Equijoin on all common fields.

Slide No:L6-10
Division

• Not supported as a primitive operator, but useful for


expressing queries like:
Find sailors who
have reserved all boats.
 |  x x, yand
• Let A have 2x fields,
– A/B =
 Ay;  
y only
B have B field y:

– i.e., A/B contains all x tuples (sailors) such that for


every y tuple (boat) in B, there is an xy tuple in A.
– Or: If the set of y values (boats) associated with an x
value (sailor) in A contains all y values in B, the x

value is in A/B.
• In general, x and y can be any lists of fields; y is the list
of fields in B, and x y is the list of fields of A.
Slide No:L6-11
Examples of Division A/B

sno pno pno pno pno


s1 p1 p2 p2 p1
s1 p2 p4 p2
s1 p3 p4
B1
s1 p4 B2
s2 p1 sno B3
s2 p2 s1 sno
s3 p2 sno
s2 s1 s1
s4 p2 s3 s4
s4 p4 s4

A A/B1 A/B2 A/B3


Slide No:L6-12
Find names of sailors who’ve reserved boat
#103

• Solution 1:  sname(( Reserves)  Sailors)


bid 103
 Solution 2:  (Temp1,  Re serves)
bid  103

 ( Temp2, Temp1  Sailors)


 sname (Temp2)

 Solution 3:  sname ( (Re serves  Sailors))


bid 103

Slide No:L6-14
Find names of sailors who’ve reserved a red boat
• Information about boat color only available in Boats; so need an
extra join:

 sname (( Boats)  Re serves  Sailors)


color ' red '
 A more efficient solution:

 sname ( ((  Boats)  Re s)  Sailors)


sid bid color ' red '

A query optimizer can find this, given the first solution!

Slide No:L6-15
Find sailors who’ve reserved a red or a green boat
• Can identify all red or green boats, then find sailors who’ve
reserved one of these boats:

 (Tempboats, ( Boats))
color ' red '  color ' green '
 sname(Tempboats  Re serves  Sailors)

 Can also define Tempboats using union! (How?)

 What happens if  is replaced by  in this query?

Slide No:L6-16
Find sailors who’ve reserved a red and a green boat
• Previous approach won’t work! Must identify sailors who’ve
reserved red boats, sailors who’ve reserved green boats, then find
the intersection (note that sid is a key for Sailors):

 (Tempred,  (( Boats)  Re serves))


sid color ' red '

 (Tempgreen,  (( Boats)  Re serves))


sid color ' green'

 sname((Tempred  Tempgreen)  Sailors)

Slide No:L6-17
Aggregate functons
For example : Find the total sum of salaries of all Female
Employees in an Organization.
•Query : G (SUM(salary)) (Female_employees)

To eliminate the duplicates, DISTINCT keyword is used.


•For example : Count the number of branches in a
university.
•Gcount-distinct (BranchName ) (StudentsDetails)

You might also like