0% found this document useful (0 votes)
2 views65 pages

02b.relational Algebra

The document provides an overview of relational algebra, including its operators such as select, project, and join, which are fundamental for querying relational databases. It explains the operations in detail, including examples and notations for each operator, as well as the conditions for set operations and the division operator. Additionally, it illustrates practical queries using these operations to manipulate and retrieve data from relational schemas.

Uploaded by

sunil
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)
2 views65 pages

02b.relational Algebra

The document provides an overview of relational algebra, including its operators such as select, project, and join, which are fundamental for querying relational databases. It explains the operations in detail, including examples and notations for each operator, as well as the conditions for set operations and the division operator. Additionally, it illustrates practical queries using these operations to manipulate and retrieve data from relational schemas.

Uploaded by

sunil
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/ 65

RNS INSTITUTE OF

Technology

REALTIONAL ALGEBRA
Sunil G L
Assistant Professor
Dept. of CSE (Data Science)
RNS Institute of Technology

1
Relational Algebra
▪ A set of operators (unary and binary) that take relation
instances as arguments and return new relations.
▪ Gives a procedural method of specifying a retrieval query.
▪ Forms the core component of a relational query engine.
▪ SQL queries are internally translated into RA expressions.
▪ Provides a framework for query optimization.

RA operations: select (), project (), cross product (),


union (⋃), intersection (∩), difference (−), join ( ⋈ )

2
The select Operator
▪ Unary operator.
▪ can be used to select those tuples of a relation that
satisfy a given condition.
▪ Notation:  ( r )
  select operator ( read as sigma)
 : selection condition
r : relation name
▪ Result: a relation with the same schema as r
consisting of the tuples in r that satisfy condition θ
▪ Select operation is commutative:
c1 (c2 ( r )) = c2 (c1 ( r ))

3
Selection Condition
• Select condition:
Basic condition or Composite condition
• Basic condition:
Either Ai <compOp> Aj or Ai <compOp> c
• Composite condition:
Basic conditions combined with logical operators
AND, OR and NOT appropriately.
• Notation:
<compOp> : one of < , ≤ , > ,  , = , 
Ai, Aj : attributes in the scheme R of r
c : constant of appropriate data type
4
Examples of select expressions
1. Obtain information about a professor with name
“giridhar”
name = “giridhar” (professor)

2. Obtain information about professors who joined the


university between 1980 and 1985
startYear ≥ 1980 ^ startYear < 1985 (professor)

5
The project Operator
▪ Unary operator.
▪ Can be used to keep only the required attributes of a
relation instance and throw away others.
▪ Notation:  A ,A , … ,A (r ) where A1,A2, … ,Ak is a list L of
1 2 k

desired attributes in the scheme of r.


▪ Result = { (v1,v2, … ,vk) | vi ∈ dom(Ai) , 1≤ i ≤ kand
there is some tuple t in r s.t
t.A1 = v1, t.A2 = v2, … , t.Ak = vk}
▪ If r1 = L(r2) then scheme of r1 is L

6
Examples of project expressions
student
rollNo name degree year sex deptNo advisor
CS04S001 Mahesh M.S 2004 M 1 CS01
CS03S001 Rajesh M.S 2003 M 1 CS02
CS04M002 Piyush M.E 2004 M 1 CS01
ES04M001 Deepak M.E 2004 M 2 ES01
ME04M001 Lalitha M.E 2004 F 3 ME01
ME03M002 Mahesh M.S 2003 M 3 ME01

 rollNo, name (student)


name (degree = “M.S” (student))
rollNo name
CS04S001 Mahesh name
CS03S001 Rajesh Mahesh

CS04M002 Piyush Rajesh

ES04M001 Deepak
Note: Mahesh is displayed only once because
ME04M001 Lalitha
project operation results in a set.
ME03M002 Mahesh

7
Size of project expression result
▪ If r1 = L(r2) then scheme of r1 is L
▪ What about the number of tuples in r1?
▪ Two cases arise:
▪ Projection List L contains some key of r2
▪ Then |r1| = |r2|
▪ Projection List L does not contain any key of r2
▪ Then |r1| ≤ |r2|

8
Set Operators on Relations
• As relations are sets of tuples, set operations are applicable
to them; but not in all cases.
• Union Compatibility : Consider two schemes R1, R2 where
R1 = (A1, A2, …, Ak) ; R2 = (B1, B2, …, Bm)
• R1 and R2 are called union-compatible if
• k = m and
• dom(Ai) = dom(Bi) for 1 ≤ i ≤ k
• Set operations – union, intersection, difference
• Applicable to two relations if their schemes are
union-compatible
• If r3 = r1 ⋃ r2 , scheme of r3 is R1 (as a convention)

9
Set Operations
r1 - relation with scheme R1
r2 - relation with scheme R2 - union compatible with R1

r1 ⋃ r2 = {t | t ∈ r1 or t ∈ r2};
r1 ∩ r2 = {t | t ∈ r1 and t ∈ r2}
r1 − r2 = {t | t ∈ r1 and t ∉ r2};

By convention, in all the cases, the scheme of the result


is that of the first operand i.e r1.

10
Cross product Operation
r1  r2
r1 A1 A2 ... Am
a11 a12 ... a1m A1 A2 ... Am B1 B 2 ... B n
a21 a22 ... a2m a11 a12 ... a1 m b11 b12 ... b1 n
as1 as2 ... asm a11 a12 ... a1 m b 21 b 22 ... b2 n
. .
. .
r1 : s tuples a11 a12 ... a 1m bt1 bt 2 ... b tn
r2 B1 B2 ... Bn a 21 a 2 2 ... a 2 m b11 b12 ... b1n
b11 b12 ... b1n a 21 a 2 2 ... a 2 m b 21 b 22 ... b 2 n
. .
b21 b22 ... b2n . .

bt1 bt2 ... btn a 21 a 22 ... a 2 m bt1 bt 2 ... btn


.
r2 : t tuples .
.
r1  r2 : s  t tuples
11
12
13
14
15
Example Query using cross product
Obtain the list of professors along with the name of their
departments

• profDetail (eId, pname,deptno) ←  empId, name, deptNo (professor)

• deptDetail (dId,dname) ←  deptId, name (department)

• profDept ← profDetail  deptDetail

• desiredProfDept ←  deptno = dId (profDept)

• result ←  eld, pname, dname (desiredProfDept)

16
Example Relational Scheme with RIC’s shown
student (rollNo, name, degree, year, sex, deptNo, advisor)

department (deptId, name, hod, phone)

professor (empId, name, sex, startYear, deptNo, phone)

course (courseId, cname, credits, deptNo)

enrollment (rollNo, courseId, sem, year, grade)

teaching (empId, courseId, sem, year, classRoom)

preRequisite (preReqCourse, courseID)

17
Join Operation
• Cross product : produces all combinations of tuples
• often only certain combinations are meaningful
• cross product is usually followed by selection

• Join : combines tuples from two relations provided they


satisfy a specified condition (join condition)
• equivalent to performing cross product followed by
selection
• a very useful operation

• Depending on the type of condition we have


• theta join
• equi join

18
Theta join
• Let r1 - relation with scheme R1 = (A1,A2,…,Am)
r2 - relation with scheme R2 =(B1,B2,…,Bn)
and R1 ∩ R2 = 
• Notation for join expression : r1 ⋈ r2 ,  - join condition
 is of the form : C1 ^ C2 ^ … ^ Cs
Ci is of the form : Aj <CompOp> Bk
<CompOp> : = , ≠, < , ≤ , > , ≥
• Scheme of the result relation
Q = (A1,A2,…,Am,B1,B2,…,Bn)
• r = {(a1,a2,…,am,b1,b2,…,bn) (a1,a2,…,am)  r1,
(b1,b2,…,bn)  r2 and (a1,a2,…,am , b1,b2,…,bn) satisfies }

19
Professor
empId name sex startYear deptNo phone
CS01 GIRIDHAR M 1984 1 22576345

CS02 KESHAV M 1989 1 22576346


MURTHY
ES01 RAJIV GUPTHA M 1980 2 22576244

ME01 TAHIR M 1999 3 22576243


NAYYAR

Courses
Department
deptId name hod phone courseId cname credits deptNo
CS635 Algorithms 3 1
1 Computer Science CS01 22576235
CS636 A.I 4 1
2 Electrical Engg. ES01 22576234 ES456 D.S.P 3 2

3 Mechanical Engg. ME01 22576233 ME650 Aero 3 3


Dynamics

20
Examples
For each department, find name sex and phone number of the head of the
department.
Prof (empId, p-name, sex, deptNo, prof-phone)
←  empId, name, sex, deptNo, phone (professor)
Result ←
 DeptId, name, hod, p-name, sex, prof-phone
(Department ⋈
(empId = hod) ^ (deptNo = deptId)
Prof)

deptId name hod p-name sex prof-phone

1 Computer CS01 Giridher M 22576235


Science
2 Electrical EE01 Rajiv M 22576234
Engg. Guptha
3 Mechanical ME01 Tahir M 22576233
Engg. Nayyar

21
Equi-join and Natural join
• Equi-join : Equality is the only comparison operator used in the
join condition
• Natural join : R1, R2 - have common attributes, say X1,X2,X3
• Join condition:
(R1.X1 = R2.X1) ^ (R1.X2 = R2.X2) ^ (R1.X3 = R2.X3)
• values of common attributes should be equal
• Schema for the result Q = R1 ⋃ (R2- {X1, X2, X3 })
•Only one copy of the common attributes is kept

• Notation for natural join : r = r1 * r2

22
Examples – Equi-join
Find courses offered by each department

 deptId, name, courseId, cname, credits ( Department ⋈(deptId = deptNo) Courses)

deptId name courseId cname credits

1 Computer CS635 Algorithms 3


Science
1 Computer CS636 A.I 4
Science
2 Electrical ES456 D.S.P 3
Engg.
3 Mechanical ME650 Aero 3
Engg. Dynamics

23
Teaching
empId courseI sem year classRo
d om
CS01 CS635 1 2005 BSB361
CS02 CS636 1 2005 BSB632
ES01 ES456 2 2004 ESB650
ME01 ME650 1 2004 MSB331

To find the courses handled by each professor


Professor * Teaching
result
empId name sex startYear deptNo phone courseId sem year classRoom
CS01 Giridhar M 1984 1 22576345 CS635 1 2005 BSB361

CS02 Keshav M 1989 1 22576346 CS636 1 2005 BSB632


Murthy
ES01 Rajiv M 1989 2 22576244 ES456 2 2004 ESB650
Guptha
ME01 Tahir M 1999 3 22576243 ME650 1 2004 MSB331
Nayyar

24
Division operator
▪ The necessary condition to determine r  s on
instances r(R) and s(S) is S ⊆ R
▪ The relation r  s is a relation on schema R – S.
A tuple t is in r  s if and only if
1) t is in  R-S (r)
2) For every tuple ts in s, there is tr in r satisfying both
a) tr [S] = ts
b) tr [R – S] = t

• Another Definition r = r1  r2
Division operator produces a relation R(X) that includes all
tuples t[X] in R1(Z) that appear in R1 in combination with
every tuple from R2(Y) where Z = X ⋃ Y

25
R = (A, B, C, D), S = (A, B), X = (C, D)
x=r s
r A B C D
s A B a1 b1 c1 d1
a1 b1 a 2 b2 c1 d1
a 2 b2 a1 b1 c2 d 2
a1 b1 c3 d 3
x C D a 2 b2 c3 d 3
c1 d1
c3 d3

(c2, d2) is not present in the result of division as it does not appear
in combination with all the tuples of s in r

26
27
28
Query using division operation

Find those students who have registered for all courses offered
in dept of Computer Science.

Step1: Get the course enrollment information for all students


studEnroll ←  name, courseId (student * enrollment)

Step2: Get the course Ids of all courses offered by CS dept


csCourse ← courseId(dname = “computer science”(courses ⋈ deptId = deptNodept))

Result : studEnroll  csCourse

Schema

29
Suppose result of step 1 is result of step 2
studEnroll csCourse
name courseId courseId
Mahesh CS635 CS635
Mahesh CS636 CS636
Rajesh CS635
Piyush CS636
Piyush CS635
Deepak ES456
Lalitha ME650
Mahesh ME650

Let’s assume for a


studEnroll  csCourse moment that student
result names are unique!
name
Mahesh
Piyush

30
Complete Set of Operators

• Are all Relational Algebra operators essential ?


Some operators can be realized through other operators

• What is the minimal set of operators ?


• The operators { , ,  , ⋃ , - }constitute a complete set
of operators
• Necessary and sufficient set of operators.
• Intersection – union and difference
• Join – cross product followed by selection
• Division – project, cross product and difference

31
Example Queries
Schema
Retrieve the list of female PhD students

 degree = ‘phD’ ^ sex = ‘F’ (student)

Obtain the name and rollNo of all female Btech students

rollNo, name ( degree = ‘BTech’ ^ sex = ‘F’ (student))

Obtain the rollNo of students who obtained an ‘E’ grade

 rollNo (student) –  rollNo ( grade = ‘E’ (enrollment))

32
More Example Queries
Obtain the department Ids for departments with no lady
professor

 deptId (dept) –  deptId ( sex = ‘F’ (professor))

Obtain the rollNo of girl students who have obtained


at least one S grade

 rollNo ( sex = ‘F’(student)) ∩  rollNo ( grade = ‘S’ (enrollment))

33
Another Example Query Schema

Obtain the names, roll numbers of students who have got S grade in
the CS370 course offered in 2006 odd semester along with his/her
advisor name.

reqStudsRollNo ←
rollNo(courseId =‘CS370’& year =‘2006’& semester = ‘odd’&grade=‘S’(enrollment))

reqStuds-Name-AdvId ( rollNo, sName, advId) ←


 rollNo, name, advisor(reqStudsRollNo * student)

result( rollNo, studentName, advisorName) ←


 rollNo, sName, name(reqStuds-Name-AdvId ⋈advId=empId professor)

34
Transitive Closure Queries Schema

Obtain the courses that are either direct or indirect prerequisites of


the course CS767.
• Indirect prerequisite – (prerequisite of )+ a prerequisite course
• Prerequisites at all levels are to be reported

levelOnePrereq(cId1) ← preReqCourse(courseId =‘CS767’(preRequisite))

levelTwoPrereq(cId2) ←
preReqCourse (preRequisite ⋈ courseId = cId1 levelOnePrereq))

Similarly, level k prerequisites can be obtained.


But, prerequisites at all levels can not be obtained as there is
no looping mechanism.

35
36
37
Outer Join Operation (1/2)
▪ Theta join, equi-join, natural join are all called inner joins . The
result of these operations contain only the matching tuples

▪ The set of operations called outer joins are used when all
tuples in relation r or relation s or both in r and s have
to be in result.

There are 3 kinds of outer joins:


Left outer join

Right outer join

Full outer join

38
39
40
41
Outer Join Operation (2/2)
Left outer join: r s
It keeps all tuples in the first, or left relation r in the result. For
some tuple t in r, if no matching tuple is found in s then
S-attributes of t are made null in the result.

Right outer join: r s


Same as above but tuples in the second relation are all kept in
the result. If necessary, R-attributes are made null.

Full outer join: r s


All the tuples in both the relations r and s are in the result.

42
Instance Data for Examples
Student
rollNo name degree year sex deptNo advisor
CS04S001 Mahesh M.S 2004 M 1 CS01
CS05S001 Amrish M.S 2003 M 1 null
CS04M002 Piyush M.E 2004 M 1 CS01
ES04M001 Deepak M.E 2004 M 2 null
ME04M001 Lalitha M.E 2004 F 3 ME01
ME03M002 Mahesh M.S 2003 M 3 ME01

Professor
empId name sex startYear deptNo phone
CS01 GIRIDHAR M 1984 1 22576345

CS02 KESHAV M 1989 1 22576346


MURTHY
ES01 RAJIV GUPTHA M 1980 2 22576244

ME01 TAHIR M 1999 3 22576243


NAYYAR

43
Left outer join

temp ← (student advisor = empId professor)

 ( (temp))
rollNo, name, advisor rollNo, student.name, professor.name

Result rollNo name advisor


CS04S001 Mahesh Giridhar
CS05S001 Amrish Null
CS04M002 Piyush Giridhar
ES04M001 Deepak Null
ME04M001 Lalitha Tahir Nayyer
ME03M002 Mahesh Tahir Nayyer

44
Right outer join

temp ← (student advisor = empId professor)

 ( (temp))
rollNo, name, advisor rollNo, student.name, professor.name

Result rollNo name advisor


CS04S001 Mahesh Giridhar
CS04M002 Piyush Giridhar
null null Keshav Murthy
null null Rajiv Guptha
ME04M001 Lalitha Tahir Nayyer
ME03M002 Mahesh Tahir Nayyer

45
Full outer join

temp ← (student advisor = empId professor)

 ( (temp))
roll no, name, advisor roll No, student.name, professor.name
Result
rollNo name advisor
CS04S001 Mahesh Giridhar
CS04M002 Piyush Giridhar
CS05S001 Amrish Null
null null Keshav Murthy
ES04M001 Deepak Null
null null Rajiv Guptha
ME04M001 Lalitha Tahir Nayyer
ME03M002 Mahesh Tahir Nayyer

46
47
Aggregate functions in
Relational Algebra
Count
Sum
Average
Min
Max

48
49
50
51
52
Relational Data Base Design using E/R diagrams to
Relational Schema
▪ E/R model and the relational model are logical representations
of real world enterprises

▪ An E/R diagram can be converted to a collection of tables

▪ For each entity set and relationship set in E/R diagram we can
have a corresponding relational table with the same name as
entity set / relationship set

▪ Each table will have multiple columns whose names are obtained
from the attributes of entity types/relationship types

53
Relational representation of strong entity sets
▪ Create a table Ti for each strong entity set Ei.

▪ Include simple attributes and simple components


of composite attributes of entity set Ei as attributes of Ti.

▪Multi-valued attributes of entities are dealt with separately.

▪ The primary key of Ei will also be the primary key of Ti.

▪ The primary key can be referred to by other tables via


foreign keys in them to capture relationships as we see later

54
Relational representation of weak entity sets
▪ Let E' be a weak entity owned by a strong/weak entity E
▪ E' is converted to a table, say R'
▪ Attributes of R' will be
▪ Attributes of the weak entity set E' and
▪ Primary key attributes of the identifying strong entity E
▪ (Or, partial key ofE + primary key of the owner of E,
if E is itself a weak entity)
• These attributes will also be a foreign key in R' referring
to the table corresponding to E

▪ Key of R' : partial key of E' + Key of E

▪ Multi-valued attributes are dealt separately as described later


55
Example
SectionN o Year
Name Credits RoomNo
CourseID
has Professor
Course Section Section

Corresponding tables are


course section
courseId name credits sectionNo courseId year roomNo professor

Primary key of section = {courseId, sectionNo}

56
Relational representation of multi-valued attributes
▪ One table for each multi-valued attribute

▪ One column for this attribute and

▪ One column for the primary key attribute of entity / relationship


set for which this is an attribute.
e.g.,
student mailIds
Name rollNo name emailId rollNo
RollNo EmailId

Student

57
Handling Binary 1:1 Relationship
▪ Let S and T be entity sets in relationship R and S', T' be the
tables corresponding to these entity sets

▪ Choose an entity set which has total participation if there is


one (says, S)

▪ Include the primary key of T' as a foreign key in S' referring


to relation T'

▪ Include all simple attributes (and simple components of


composite attributes) of R as attributes of S'

▪ We can do the other way round too


– lot of null values
58
Example
HostelName
RollNo homeAddress
Name
1
resides 1 RoomNo
STUDENT Hostel
In

Note: Assuming every student resides in hostel. address


S-STUDENT R-residesIn T-Hostel Room

Student Hostel
RollNo Name homeAddress RoomId RoomNo HostelName address

Foreign key name need


not be same as primary key
of the other relation

59
Handling 1:N Relationship
▪ Let S be the participating entity on the N-side and T the other
entity. Let S' and T' be the corresponding tables.

▪ Include primary key of T' as foreign key in S'

▪ Include any simple attribute (and simple components of


composite attributes) of 1:N relation type as attributes of S'

60
Example
Name
Phone ProfID RollNo
Name

Professor 1 guides N Student

Student Professor
RollNo Name profid ProfId Name phone

61
Handling M:N relationship
▪ Make a separate table T for this relationship R between entity
sets E1 and E2.
Let R1 and R2 be the tables corresponding to E1 and E2.

▪ Include primary key attributes of R1 and R2 as foreign keys


in T. Their combination is the primary key in T.

M N
E1 R E2

R1 T R2
PK1 FK1 FK2 PK2

62
Example
Name
Name CourseID
RollNo

Student M enrolls N Course

student enrollment course


name rollNo rollNo courseId name courseID

Primary key of enrollment table is {RollNo, CourseID}

63
Handling Recursive relationships
▪ Make a table T for the participating entity set E
( this might already be existing)
and one table for recursive relationship R.

CourseTable
Example
M is N CourseID Credits Timing
PreReq
Of

Course PreRequisiteTable
Timing
preReqCourse CourseID
CourseID
Credits

64
Thank You

65

You might also like