0% found this document useful (0 votes)
14 views52 pages

Chapter 6 Relational Algebra and Relational Calculus

Chapter 6 covers Relational Algebra and Calculus, detailing the operations and symbols used in relational databases. It discusses the role of relational algebra in DBMS, various operations like selection, projection, union, and join, as well as their properties and limitations. Additionally, it introduces relational calculus and structured query languages (SQL) with their respective components and constraints.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views52 pages

Chapter 6 Relational Algebra and Relational Calculus

Chapter 6 covers Relational Algebra and Calculus, detailing the operations and symbols used in relational databases. It discusses the role of relational algebra in DBMS, various operations like selection, projection, union, and join, as well as their properties and limitations. Additionally, it introduces relational calculus and structured query languages (SQL) with their respective components and constraints.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 52

CHAPTER SIX

Relational Algebra and Calculus

1
Chapter 6-1
Chapter Outline
6.1.Relational Algebra
6.1.1.Role of Relational Algebra in DBMS
6.1.2.Relational Algebra Operation Notations or Symbols
6.1.3.Relational Algebra Operations
6.1.3.1.Set Operations
6.1.3.2.Database Operations
6.1.4.Advantages of Relational Algebra
6.1.5.Limitations of Relational Algebra

6.2.Relational calculus
6.2.1. Tuple-oriented Relational Calculus
6.2.2. Domain Relational Calculus
6.2.3. Quantifiers in Relation Calculus

Chapter 6-2
Chapter Outline (Contd.)
6.3. Structured Query Languages (SQL)
6.3.1. SQL Languages (DML, DDL, DCL, TCL)
6.3.2. SQL Datatypes
6.3.3. SQL Selection and Projection Operation
6.3.4. SQL Aggregate Functions
6.3.5. SQL Table Modification
6.3.6. SQL Constraints
6.3.7. SQL Set and Join Operations
6.3.8. Quires and Subqueries (nested queries)

6.4.Limitations of SQL

Chapter 6-3
Relational Algebra

4
Chapter 6-4
Relational Algebra

⚫ Relational algebra refers to a procedural query language that


takes relation instances as input and returns relation instances
as output.

⚫ It performs queries with the help of operators.

⚫ A binary or unary operator can be used.

⚫ Relational algebra is a collection of operations that users can


perform on relations to obtain a desired result.

Chapter 6-5
Relational Algebra
⚫ The algebra operations thus produce new relations

– These can be further manipulated using operations of the


same algebra.

⚫ The basic set of operations for the relational model is known as


the relational algebra. These operations enable a user to specify
basic retrieval requests.

⚫ The result of a retrieval is a new relation, which may have been


formed from one or more relations.

Chapter 6-6
Relational Algebra
⚫ A sequence of relational algebra operations forms a relational
algebra expression, whose result will also be a relation that
represents the result of a database query (or retrieval request).

⚫ Basic Relational Algebra operations:


– Selection ( σ ): Selects a subset of tuples from a relation.

– Projection ( π ): Selects columns from a relation.

– Cross-product ( × ): Allows us to combine two relations.

– Set-difference ( − ): Tuples in relation 1, but not in relation 2.

– Union ( ∪ ): Tuples in relation 1 and in relation 2

Chapter 6-7
Unary Relational Operations
⚫ SELECT Operation
– SELECT operation is used to select a subset of the tuples from a
relation that satisfy a selection condition. It is a filter that keeps
only those tuples that satisfy a qualifying condition those
satisfying the condition are selected while others are discarded.
– In general, the select operation is denoted by  <selection condition>(R)
where the symbol  (sigma) is used to denote the select operator,
and the selection condition is a Boolean expression specified on
the attributes of relation R.
– Example: To select the EMPLOYEE tuples whose department
number is four or those whose salary is greater than $30,000 the
following notation is used:
DNO = 4 (EMPLOYEE)
SALARY > 30,000 (EMPLOYEE)
Chapter 6-8
Unary Relational Operations
SELECT Operation Properties

– The SELECT operation  <selection condition>(R) produces a relation S that


has the same schema as R

– The SELECT operation  is commutative; i.e.,


 <condition1>( < condition2> ( R)) =  <condition2> ( < condition1> ( R))

– A cascaded SELECT operation may be applied in any order; i.e.,


 <condition1>( < condition2> ( <condition3> ( R))
=  <condition2> ( < condition3> ( < condition1> ( R)))

– A cascaded SELECT operation may be replaced by a single selection


with a conjunction of all the conditions; i.e.,
 <condition1>( < condition2> ( <condition3> ( R))
=  <condition1> AND < condition2> AND < condition3> ( R)))

Chapter 6-9
Unary Relational Operations (cont.)
⚫ PROJECT Operation
– This operation selects certain columns from the table and discards
the other columns. The PROJECT creates a vertical partitioning –
one with the needed columns (attributes) containing results of the
operation and other containing the discarded Columns.
– The general form of the project operation is <attribute list>(R)
where  (pi) is the symbol used to represent the project operation
and <attribute list> is the desired list of attributes from the
attributes of relation R.
– The project operation removes any duplicate tuples, so the result
of the project operation is a set of tuples and hence a valid relation.
– Example: To list each employee’s first and last name and salary,
the following is used:
 LNAME, FNAME,SALARY (EMPLOYEE)
Chapter 6-10
Unary Relational Operations (cont.)

PROJECT Operation Properties


– The number of tuples in the result of projection  <list> (R)is

always less or equal to the number of tuples in R.

– If the list of attributes includes a key of R, then the number


of tuples is equal to the number of tuples in R.

–  <list1> ( <list2> (R) ) =  <list1> (R) as long as <list2> contains


the attributes in <list2>

Chapter 6-11
Unary Relational Operations (cont.)
⚫ Rename Operation
– We may want to apply several relational algebra operations one
after the other. Either we can write the operations as a single
relational algebra expression by nesting the operations, or we can
apply one operation at a time and create intermediate result
relations. In the latter case, we must give names to the relations
that hold the intermediate results.
– Example: To retrieve the first name, last name, and salary of all
employees who work in department number 5, we must apply a
select and a project operation. We can write a single relational
algebra expression as follows:
FNAME, LNAME, SALARY( DNO=5(EMPLOYEE))
OR We can explicitly show the sequence of operations, giving a name to each
intermediate relation:
DEP5_EMPS   DNO=5(EMPLOYEE)
RESULT   FNAME, LNAME, SALARY (DEP5_EMPS)
Chapter 6-12
Unary Relational Operations (cont.)
⚫ Rename Operation (cont.)

⚫ The rename operator is 


The general Rename operation can be expressed by any of the
following forms:
−  S (B1, B2, …, Bn ) ( R) is a renamed relation S based on R with
column names B1, B2, …..Bn

−  S ( R) is a renamed relation S based on R (which does not


specify column names).

−  (B1, B2, …, Bn ) ( R) is a renamed relation with column names


B1, B1, …..Bn which does not specify a new relation name.
Chapter 6-13
Unary Relational Operations (cont.)
⚫ Rename Operation (cont.)
⚫ Example:
– LastName, SocSocNo (Employee)
– Output schema:
Answer(LastName, SocSocNo)
Employee
Name SSN
John 999999999
Tony 777777777

LastName, SocSocNo (Employee)


LastName SocSocNo
John 999999999
Tony 777777777
Chapter 6-14
Relational Algebra Operations From
Set Theory
⚫ UNION Operation
– UNION is symbolized by ∪ symbol. It includes all tuples that are in tables
R or in S. It also eliminates duplicate tuples. So, set R UNION set S would
be expressed as:

– The result <- R ∪ S

– The result of this operation, denoted by R  S, is a relation that includes


all tuples that are either in R or in S or in both R and S.

– Duplicate tuples are eliminated.

– A union operation to be valid, the following conditions must hold


• R and S must be the same number of attributes.
• Attribute domains need to be compatible.
• Duplicate tuples should be automatically removed.
Chapter 6-15
Relational Algebra Operations From
Set Theory
⚫ UNION Operation
– UNION Example

RUS

Chapter 6-16
Relational Algebra Operations From
Set Theory
⚫ Type Compatibility

– The operand relations R1(A1, A2, ..., An) and R2(B1, B2, ..., Bn)
must have the same number of attributes, and the domains of
corresponding attributes must be compatible; that is,
dom(Ai)=dom(Bi) for i=1, 2, ..., n.

– The resulting relation for R1R2,R1  R2, or R1-R2 has the


same attribute names as the first operand relation R1 (by
convention).

Chapter 6-17
Relational Algebra Operations From
Set Theory
⚫ UNION Example

STUDENTINSTRUCTOR

Chapter 6-18
Relational Algebra Operations From Set
Theory (cont.)
⚫ INTERSECTION OPERATION
– The result of this operation, denoted by R  S, is a relation that includes all tuples that
are in both R and S. The two operands must be "type compatible“

– Example: The result of the intersection operation (figure below)


includes only those who are both students and instructors.

STUDENT  INSTRUCTOR

Chapter 6-19
Relational Algebra Operations From Set
Theory (cont.)
⚫ Set Difference (or MINUS) Operation
– The result of this operation, denoted by R - S, is a relation that includes all
tuples that are in R but not in S. The two operands must be "type
compatible”.

– Example: The figure shows the names of students who are not instructors,
and the names of instructors who are not students.

STUDENT-INSTRUCTOR

INSTRUCTOR-STUDENT

Chapter 6-20
Relational Algebra Operations From Set
Theory (cont.)
⚫ Notice that both union and intersection are commutative operations; that
is
R  S = S  R, and R  S = S  R

⚫ Both union and intersection can be treated as n-ary operations


applicable to any number of relations as both are associative operations;
that is
R  (S  T) = (R  S)  T, and (R  S)  T = R  (S  T)

⚫ The minus operation is not commutative; that is, in general


R-S≠S–R

Chapter 6-21
Relational Algebra Operations From Set
Theory (cont.)
⚫ CARTESIAN (or cross product) Operation
– Cartesian Product is an operation used to merge columns from two
relations.
– This operation is used to combine tuples from two relations in a
combinatorial fashion.
– In general, the result of R(A1, A2, . . ., An) x S(B1, B2, . . ., Bm) is a
relation Q with degree n + m attributes Q(A1, A2, . . ., An, B1, B2, . .
., Bm), in that order. The resulting relation Q has one tuple for each
combination of tuples one from R and one from S.
– Hence, if R has nR tuples (denoted as |R| = nR ), and S has nS tuples,
then
| R x S | will have nR * nS tuples.
– The two operands do NOT have to be "type compatible”
– It is also called Cross Product or Cross Join.
Chapter 6-22
Relational Algebra Operations From Set
Theory (cont.)
• Consider the two tables below Female x Male

Chapter 6-23
Binary Relational Operations
⚫ JOIN Operation
– The sequence of cartesian product followed by select is used
quite commonly to identify and select related tuples from two
relations, a special operation, called JOIN.
• It is denoted by a ⨝
– This operation is very important for any relational database
with more than a single relation, because it allows us to process
relationships among relations.
– The general form of a join operation on two relations R(A1, A2,
. . ., An) and S(B1, B2, . . ., Bm) is:
R ⨝ <join condition>S
where R and S can be any relations that result from general
relational algebra expressions.
Chapter 6-24
Binary Relational Operations (cont.)
Example: Suppose that we want to retrieve the name of
the manager of each department. To get the manager’s
name, we need to combine each DEPARTMENT tuple
with the EMPLOYEE tuple whose SSN value matches
the MGRSSN value in the department tuple. We do this
by using the join operation.
DEPT_MGR  DEPARTMENT MGRSSN=SSN
EMPLOYEE

Chapter 6-25
Binary Relational Operations (cont.)
⚫ EQUIJOIN Operation

– The most common use of join involves join conditions with equality

comparisons only. Such a join, where the only comparison operator used is

=, is called an EQUIJOIN.

– In the result of an EQUIJOIN we always have one or more pairs of

attributes (whose names need not be identical) that have identical values

in every tuple.

– The JOIN seen in the previous example was EQUIJOIN.

Chapter 6-26
Binary Relational Operations (cont.)
⚫ NATURAL JOIN Operation
– Natural join can only be performed if there is a common attribute (column)
between the relations. The name and type of the attribute must be same.

– Because one of each pair of attributes with identical values is superfluous,


a new operation called natural join denoted by * was created to get rid of
the second (superfluous) attribute in an EQUIJOIN condition.

– The standard definition of natural join requires that the two join attributes,
or each pair of corresponding join attributes, have the same name in both
relations. If this is not the case, a renaming operation is applied first.

Chapter 6-27
Binary Relational Operations (cont.)

Natural Join
⚫R= A B S= B C
X Y Z U
X Z V W
Y Z Z V
Z V

A B C
⚫R || S= X Z U
X Z V
Y Z U
Y Z V
Z V W
Chapter
Slide6-28
- 28
Complete Set of Relational Operations

⚫ The set of operations including select , project  ,


union , set difference - , and cartesian product X
is called a complete set because any other relational
algebra expression can be expressed by a combination
of these five operations.
⚫For example:
R  S = (R  S ) – ((R − S)  (S − R))
R <join condition>S =  <join condition> (R X S)
Chapter 6-29
Recap of Relational Algebra Operations

Chapter 6-30
Additional Relational Operations
⚫ Aggregate Functions and Grouping

– A type of request that cannot be expressed in the basic relational algebra


is to specify mathematical aggregate functions on collections of values
from the database.

– Examples of such functions include retrieving the average or total salary


of all employees or the total number of employee tuples. These functions
are used in simple statistical queries that summarize information from
the database tuples.

– Common functions applied to collections of numeric values include


SUM, AVERAGE, MAXIMUM, and MINIMUM. The COUNT
function is used for counting tuples or values.
Chapter 6-31
Additional Relational Operations (cont.)

Chapter 6-32
Additional Relational Operations (cont.)
Use of the Functional operator ℱ

▪ ℱMAX Salary (Employee) retrieves the maximum salary value


from the Employee relation
▪ ℱMIN Salary (Employee) retrieves the minimum Salary value
from the Employee relation
▪ ℱSUM Salary (Employee) retrieves the sum of the Salary from
the Employee relation
▪ DNO ℱCOUNT SSN, AVERAGE Salary (Employee) groups employees by
DNO (department number) and computes the count of
employees and average salary per department.[ Note: count
just counts the number of rows, without removing duplicates]

Chapter 6-33
Additional Relational Operations (cont.)
⚫ The OUTER JOIN Operation
– In NATURAL JOIN tuples without a matching (or related) tuple are eliminated
from the join result. Tuples with null in the join attributes are also eliminated.
This amounts to loss of information.
– A set of operations, called outer joins, can be used when we want to keep all the
tuples in R, or all those in S, or all those in both relations in the result of the
join, regardless of whether or not they have matching tuples in the other relation.
– The left outer join operation keeps every tuple in the first or left relation R in
R S; if no matching tuple is found in S, then the attributes of S in the join
result are filled or “padded” with null values.
– A similar operation, right outer join, keeps every tuple in the second or right
relation S in the result of R S.
– A third operation, full outer join, denoted by keeps all tuples in both the
left and the right relations when no matching tuples are found, padding them
with null values as needed.

Chapter 6-34
Additional Relational Operations (cont.)

Chapter 6-35
Additional Relational Operations (cont.)
⚫ OUTER UNION Operations
– The outer union operation was developed to take the union of tuples from two
relations if the relations are not union compatible.
– This operation will take the union of tuples in two relations R(X, Y) and S(X, Z)
that are partially compatible, meaning that only some of their attributes, say X,
are union compatible.
– The attributes that are union compatible are represented only once in the result,
and those attributes that are not union compatible from either relation are also
kept in the result relation T(X, Y, Z).
– Example: An outer union can be applied to two relations whose schemas are
STUDENT(Name, SSN, Department, Advisor) and INSTRUCTOR(Name, SSN,
Department, Rank). Tuples from the two relations are matched based on having
the same combination of values of the shared attributes—Name, SSN,
Department. If a student is also an instructor, both Advisor and Rank will have a
value; otherwise, one of these two attributes will be null.
The result relation STUDENT_OR_INSTRUCTOR will have the following
attributes:
STUDENT_OR_INSTRUCTOR (Name, SSN, Department, Advisor, Rank)
Chapter 6-36
Examples of Queries in Relational Algebra
⚫ Q1: Retrieve the name and address of all employees who
work for the ‘Research’ department.
RESEARCH_DEPT   DNAME=’Research’ (DEPARTMENT)
RESEARCH_EMPS  (RESEARCH_DEPT DNUMBER=

DNOEMPLOYEEEMPLOYEE)

RESULT   FNAME, LNAME, ADDRESS (RESEARCH_EMPS)

⚫ Q6: Retrieve the names of employees who have no


dependents.
ALL_EMPS   SSN(EMPLOYEE)

EMPS_WITH_DEPS(SSN)   ESSN(DEPENDENT)
EMPS_WITHOUT_DEPS  (ALL_EMPS - EMPS_WITH_DEPS)
RESULT   LNAME, FNAME (EMPS_WITHOUT_DEPS * EMPLOYEE)
Chapter 6-37
Relational algebra – solved exercise
1. Consider the following relational database schema consisting
of the four relation schemas:

✓ passenger ( pid, pname, pgender, pcity)

✓ agency ( aid, aname, acity)

✓ flight (fid, fdate, time, src, dest)

✓ booking (pid, aid, fid, fdate)

⚫ Answer the following questions using relational algebra


queries;

386-38
Chapter
Relational algebra – solved exercise
a. Get the complete details of all flights to New Delhi.
Soln:- σ destination = “New Delhi” (flight)
b. Get the details about all flights from Chennai to New Delhi.
Soln:- σ src = “Chennai” ^ dest = “New Delhi” (flight)
c. Find only the flight numbers for passenger with pid 123 for
flights to Chennai before 06/11/2020.
Soln:- Π fid (σ pid = 123 (booking) ⨝ σ dest = “Chennai” ^ fdate <
06/11/2020 (flight))
[Hint: Given conditions are pid, dest, and fdate. To get the flight
id for a passenger given a pid, we have two tables flight and
booking to be joined with necessary conditions. From the result,
the flight id can be projected]

396-39
Chapter
Relational algebra – solved exercise
d. Find the passenger names for passengers who have bookings
on at least one flight.

Soln:- Π pname (passenger ⨝ booking)

e. Find the passenger names for those who do not have any
bookings in any flights.

Soln:- Π pname ((Π pid (passenger) - Π pid (booking)) ⨝


passenger)
➢ Hint: here applied a set difference operation. The set difference operation
returns only pids that have no booking. The result is joined with passenger
table to get the passenger names.] 406-40
Chapter
Relational algebra – solved exercise
f. Find the agency names for agencies that located in the same
city as passenger with passenger id 123.

Soln:-Πaname (agency ⨝ acity = pcity(σpid =123 (passenger)))

➢ Hint: we performed a theta join on equality conditions (equi


join) here. This is done between details of passenger 123 and
the agency table to get the valid records where the city values
are same. From the results, aname is projected.]

416-41
Chapter
Relational algebra – solved exercise
g. Get the details of flights that are scheduled on both dates
01/12/2020 and 02/12/2020 at 16:00 hours.

Soln:- (σ fdate = 01/12/2020 ^ time = 16:00 (flight)) ∩ (σ fdate =

02/12/2020 ^ time = 16:00 (flight))

⚫ [Hint: the requirement is for flight details for both dates in common.
Hence, set intersection is used between the temporary relations generated
from application of various conditions.]

h. Get the details of flights that are scheduled on either of the


dates 01/12/2020 or 02/12/2020 or both at 16:00 hours.

Soln:- (σ fdate = 01/12/2020 ^ time = 16:00 (flight)) ∪ (σ fdate =

02/12/2020 ^ time = 16:00 (flight))


426-42
Chapter
Relational algebra – solved exercise
i. Find the agency names for agencies who do not have any
bookings for passenger with id 123.
Soln:- Π aname (agency ⨝ (Π aid (agency) – Π aid (σ pid = 123
(booking)))
j. Find the details of all male passengers who are associated
with Jet agency.
Soln:- Π passengers.pid, pname, pcity (σ pgender = “Male” (passengers
⨝ booking ⨝ agency))
➢ Hint: To get the link between passengers and agency, we need to join all
three tables passengers, booking, and agency with necessary condition.
Here, agency links both passengers and agency. As we have performed
natural join operation between all three tables, the degree of the result will
consist of all attributes from all the three tables. Hence, we project only
passengers details as these are mentioned as required.]

436-43
Chapter
Relational Calculus

Chapter 6-44
Relational Calculus
⚫ Comes in two flavors: Tuple relational calculus
(TRC) and Domain relational calculus (DRC).
⚫ Calculus has variables, constants, comparison ops,
logical connectives, and quantifiers.
– TRC: Variables range over (i.e., get bound to) tuples.
– DRC: Variables range over domain elements (= field values).
– Both TRC and DRC are simple subsets of first-order logic.
⚫ Expressions in the calculus are called formulas. An
answer tuple is essentially an assignment of
constants to variables that make the formula evaluate
to true.
Chapter 6-45
Tuple Relational Calculus
⚫Query has the form: { T | p(T)}

Answer includes all tuples T that


make the formula p(T) be true.

Formula is recursively defined, starting with


simple atomic formulas (getting tuples from
relations or making comparisons of values),
and building bigger and better formulas using
the logical connectives.
Chapter 6-46
TRC Formulas
⚫Atomic formula:
– R  Rel, or R.a op S.b, or R.a op constant
– op is one of , , =, , , 
⚫Formula:
– an atomic formula, or
 p, p  q, p q
– , where p and q are formulas, or
X ( p( X))
– , where variable X is free in p(X), or
 X ( p( X))
– , where variable X is free in p(X)

Chapter 6-47
Free and Bound Variables

⚫ The use of quantifiers X and X in a


formula is said to bind X.
– A variable that is not bound is free.

⚫ Let us revisit the definition of a query: {T|p(T)}

There is an important restriction: the variable


T that appears to the left of `|’ must be the
only free variable in the formula p(...).

Chapter 6-48
Find all sailors with a rating above 7

⚫{S | S  Sailors ^ S.rating > 7}


⚫Query is evaluated on an instance of Sailors
⚫Tuple variable S is instantiated to each tuple
of this instance in turn, and the condition
“S.rating > 7” is applied to each such tuple.
⚫Answer contains all instances of S (which are
tuples of Sailors) satisfying the condition.

Chapter 6-49
Find sailors rated > 7 who’ve reserved
boat #103

⚫{S | (S  Sailors) ^ (S.rating > 7) ^ ( R 


Reserves (R.sid = S.sid ^ R.bid = 103))}
⚫Note the use of  to find a tuple in
Reserves that `joins with’ the Sailors tuple
under consideration.
⚫R is bound, S is not

Chapter 6-50
Unsafe Queries, Expressive Power
⚫ It is possible to write syntactically correct calculus
queries that have an infinite number of answers!
Such queries are called unsafe.
S |  S  Sailors
 
– e.g., 









   
 

⚫ It is known that every query that can be


expressed in relational algebra can be expressed
as a safe query in DRC / TRC; the converse is
also true.
⚫ Relational Completeness: Query language (e.g.,
SQL) can express every query that is expressible
in relational algebra/calculus.
Chapter 6-51
Summary
⚫ The relational model has rigorously defined query languages that are
simple and powerful.

⚫ Relational algebra is more operational; useful as internal representation


for query evaluation plans.

⚫ Relational calculus is non-operational, and users define queries in terms


of what they want, not in terms of how to compute it. (Declarativeness.)

⚫ Several ways of expressing a given query; a query optimizer should


choose the most efficient version.

⚫ Algebra and safe calculus have same expressive power, leading to the
notion of relational completeness.
Chapter 6-52

You might also like