Chap6-Relational Algebra

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

Relational Data Model and

Relational Algebra
Chapter 6
Relational Algebra
• Definition of relational Algebra
• Purpose of Relational Algebra
• Relational algebra Operations
• Join
• Types of join
• Aggregate function
• ER Diagram to Relational Model
• More Example
Relational Algebra
• Definition:
– Relational algebra is a procedural query language.

– It consists of a set of operations that takes one or


more relations as input and produce a new
relation as their result.
Relations, Entities, Tables
Relational model E/R Diagram SQL
Relation Entity Table
Tuple Instance Row
Attribute Attribute Column or Field
Foreign Key M:1 Relationship Foreign Key
Primary Key Primary Key
Query language
Query languages: Allow manipulation and retrieval of data from a database.
These are categorized as being either procedural or non procedural.

Procedural:
The user instructs the system to perform a sequence of operations on the
database to compute the desired result.
PL/SQL is Procedural.

Non-Procedural:
In contrast the non-procedural languages user specify what they want and do
not specify how to do.
SQL is Non-Procedural.
Role of Relational algebra in DBMS

Relational Algebra: useful for


representing execution plans.
• The operations of relational algebra can be
divided into two groups:
– Set operations : each relation is defined to be set
of tuples in relational model.
• UNION
• INTERSECTION
• SET DIFFERENCE
• CARTESIAN PRODUCT
– Other group consists of operations developed for
relational databases:
• SELECT
• PROJECT
• JOIN
Unary Relational Operations
Unary operators :operators can be applied to a single
relations
• SELECT (symbol:  (sigma))
• PROJECT (symbol: (pi))
• RENAME (symbol:  (rho))
Binary operators : Needs more than relations as input and
produce a new relation
• Cartesian product: (Symbol : x )
• Join (symbol: )
Unary Relational Operations
• The SELECT Operation: selects a subset of the tuples from a relation
that satisfy a selection condition.
• Notation:  p(r) σ(sigma) is used to denote the SELECT operator, p is
selection condition ( boolean expression )
• Multiple condition can be connected by  (and),  (or),  (not)
• Student σrating>8(Student)
Sid Sname Rating Age
Sid Sname Rating Age
11 Ramesh 9 25
11 Ramesh 9 25
12 Mamatha 8 27
14 Akash 9 28
13 Asha 7 30
14 Akash 9 28
Sid Sname Rating Age
• σrating>8 ^ age<30(Student) 11 Ramesh 9 25
14 Akash 9 28
• The PROJECT Operation: selects specified columns from the
table and discards the other columns.
• Notation:  A1 , A2 ,, Ak (r )

• where A1, A2 are the desired list of attributes and r


is a relation name.
• Stud πage(Stud) πsid,age(Stud)
Sid Sname Rating Age
Age Sid Age
11 Ramesh 9 25
25 11 25
12 Mamatha 8 27
27 12 27
13 Asha 7 30
30 13 30
14 Akash 9 28
28 14 28
Selection and Projection
• Select - Selects rows that satisfy selection
condition.
• Project - selects specified columns

sid sname rating age


28 yuppy 9 35.0 sname rating
31 lubber 8 55.5
yuppy 9
44 guppy 5 35.0
58 rusty 10 35.0 rusty 10
 rating 8(S2)  sname,rating( rating 8(S 2))
Relational Algebra Operations from Set Theory
(Union,Intersection an Minus Operation)
• Union: 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. Notation: r  s
• Defined as:
r  s = {t | t  r or t  s}
• For r  s to be valid.
1. r, s must have same number of attributes
2. The attribute domains must be compatible
Relational Algebra Operations from Set Theory
(Union,Intersection an Minus Operation)
• Intersection: denoted by R ∩ S, is a relation that
includes all tuples that are in both R and S.
• Notation r ∩ s
• Defined as:
r ∩ s = {t | t  r and t  s}
• Set intersection must be taken between compatible
relations.
– r and s must have the same attribute
– attribute domains of r and s must be compatible
Relational Algebra Operations from Set Theory
(Union,Intersection an Minus Operation)
• Set Difference(or Minus):denoted by R-S, is a relation
that includes all tuples that are in R but not in S.
Notation: r – s
• Defined as:
r – s = {t | t  r and t  s}
• Set differences must be taken between compatible
relations.
– r and s must have the same attributes
– attribute domains of r and s must be compatible
• S1 S2
Sid Sname Rating Age Sid Sname Rating Age
11 Ramesh 9 25 11 Ramesh 9 25
12 Mamatha 8 27 19 Kavitha 10 27
13 Asha 7 30 13 Asha 7 30
14 Akash 9 28 16 Bharath 9 31

• S1 ᴜ S2 S1 ∩ S2
Sid Sname Rating Age
Sid Sname Rating Age
11 Ramesh 9 25
11 Ramesh 9 25
13 Asha 7 30
12 Mamatha 8 27
13 Asha »7 30 S1 – S2
14 Akash 9 28
Sid Sname Rating Age
19 Kavitha 10 27
12 Mamatha 8 27
16 Bharath 9 31
14 Akash 9 28
Set Difference
sid sname rating age
sid sname rating age
22 dustin 7 45.0
22 dustin 7 45.0
31 lubber 8 55.5 S1 S2
58 rusty 10 35.0
S1

sid sname rating age sid sname rating age


28 yuppy 9 35.0 28 yuppy 9 35.0
31 lubber 8 55.5 44 guppy 5 35.0
44 guppy 5 35.0
S2 – S1
58 rusty 10 35.0
S2 S1-S2 not equal to S2-S1
• Used to rename a relation, or columns in the
relation.
Boats (bid, name, color) Ship (bid, name, color)

ρ Ship (Boats)

Boats (bid, name, color) Ship (sid, sname, shade)

ρ Ship (sid, sname, shade) (Boats)


Binary Relational Operations
• Join Operation: used to combine information from two
or more relations. ( )
– Rows of 2 table are combined based on the given column(s)
values.
– The tables being joined must have one common column
– Generic Join operator
• Types of join
• Cross join
• Inner join – only those tuples that satisfy the matching criteria are
included, while the rest are excluded. Possibility of loss of
information.
– Equi-join
• Natural join
• Outer join – along with tuples that satisfy the matching criteria, also
include some or all tuples that do not match the
criteria. No loss of information
– Left outer join
– Right outer join
– Full outer join
• Self-join- used to join a table to itself, as if the tables were two tables.
Binary Relational Operations
• The Cartesian Product (or Cross Product) Operation : Also called
CROSS JOIN – denoted by X.
• Used to combine tuples from two relations in a combinatorial
fashion.
•Each and every column of the first table will combine with
each and every column of the second table.

• R S RxS
a 1 a 1
b 2 a 2
3 a 3
b 1
b 2
b 3
R1 Cross Product Example
S1
sid sname rating age
22 xxx 7 45.0 sid bid day
31 yyy 8 55.5 22 101 10/10/96
58 zzz 10 35.0 58 103 11/12/96

(sid) sname rating age (sid) bid day


22 xxx 7 45.0 22 101 10/10/96
22 xxx 7 45.0 58 103 11/12/96
R1 X S1 =
31 yyy 8 55.5 22 101 10/10/96
31 yyy 8 55.5 58 103 11/12/96
58 zzz 10 35.0 22 101 10/10/96
58 zzz 10 35.0 58 103 11/12/96
Cross Product Example
• Account Depositor
Ano Bname Balanca Dname Ano
101 JP Naga 10000 Sumith 101
102 BTM 20000 Ravi 102
Kiran 103
• Find customer name having balance atleast <15000
Acc.Ano Bname Balanca Dname d.Ano
101 JP Naga 10000 Sumith 101
101 JP Naga 10000 Ravi 102
101 JP Naga 10000 Kiran 103
102 BTM 20000 Sumith 101
102 BTM 20000 Ravi 102
102 BTM 20000 Kiran 103

 Dname( a.ano  D.ano^bal15000( AcuntXDepost))


• EQUI – JOIN:(Inner Join)
Links tables by selecting rows with common values for common
attribute(s) & Does not include rows that are unmatched
Eg: EMP DEPART
NAME OFFICE DEPT SALARY DEPT MAIN OFFICE PHONE
Sumith 400 CS 25000 CS 404 2436789
Ravi 220 Econ 30000 Econ 200 2378658
Kiran 160 Elec 35000 Fin 501 2356297
Sathish 420 Econ 40000 Hist 100 2745897

• Eg: EMP emp.dept=depart.dept DEPART


NAME OFFICE emp.DEPT SALARY Depart.DEPT MAIN OFFICE PHONE
Sumith 400 CS 25000 CS 404 2436789
Ravi 220 Econ 30000 Econ 200 2378658
Sathish 420 Econ 40000 Econ 200 2378658
• NATURAL JOIN: Links tables by selecting rows with common
values in common attribute(s) and Does not include rows that
are unmatched
• similar to EQUI JOIN but natural join eliminates
duplicate columns for the joining columns.

NAME OFFICE DEPT SALARY MAIN OFFICE PHONE


Sumith 400 CS 25000 404 2436789
Ravi 220 Econ 30000 200 2378658
Sathish 420 Econ 40000 200 2378658
• NON-EQUI JOIN: joins two or more tables based on non
equaling conditions.
• Eg: EMP emp.dept!=depart.dept DEPART

NAME OFFICE DEPT SALARY DEPT MAIN OFFICE PHONE


Sumith 400 CS 25000 Econ 200 2378658
Sumith 400 CS 25000 Fin 501 2356297
Sumith 400 CS 25000 Hist 100 2745897
Ravi 220 Econ 30000 CS 404 2436789
Ravi 220 Econ 30000 Fin 501 2356297
Ravi 220 Econ 30000 Hist 100 2745897
Kiran 160 Elec 35000 CS 404 2436789
Kiran 160 Elec 35000 Econ 200 2378658
Kiran 160 Elec 35000 Fin 501 2356297
Kiran 160 Elec 35000 Hist 100 2745897
Sathish 420 Econ 40000 CS 404 2436789
Sathish 420 Econ 40000 Fin 501 2356297
Sathish 420 Econ 40000 Hist 100 2745897
• OUTER JOINS: 3 types
– Left outer join :includes all tuples in the left hand relation
and only those matching tuples from the right hand relation.
– Right outer join :includes all tuples in the right hand relation
and only those matching tuples from the left hand relation.
– Full outer join : includes all tuples in the left hand relation
and from the right hand relation.
• Eg:student Course
SNO NAME AGE Sno Cname Fees
S1 C1 1000
S1 N1 21
S3 C3 3000
S2 N2 22
S5 C5 5000
Eg:S3Left outer
N3join: Student
23 Course
S4 N4 24

SNO NAME AGE Cname Fees


S1 N1 21 C1 1000
Left outer joinS2
: includesN2
all tuples22
in the left hand
NullrelationNull
and only those matching tuples
from the right hand relation
S3 N3 23 C3 3000
S4 N4 24 Null Null
• Eg: student Course
SNO NAME AGE Sno Cname Fees
S1 C1 1000
S1 N1 21
S3 C3 3000
S2 N2 22
Eg:S3Right outer S5 C5 5000
N3 join: Student
23 Course
S4 N4 24

SNO NAME AGE Cname Fees


S1 N1 21 C1 1000
Right outer join :includes all tuples in the right hand relation and only those matching tuples
from the leftS3 N3
hand relation. 23 C3 3000
S5 Null Null C5 5000
• Eg: student Course
SNO NAME AGE Sno Cname Fees
S1 C1 1000
S1 N1 21
S3 C3 3000
S2 N2 22
S5 C5 5000
Eg:S3Full outer
N3join: Student
23 Course
S4 N4 24

SNO NAME AGE Cname Fees


S1 N1 21 C1 1000
Full outer joinS2 : includes
N2 all22
tuples in theNull
left hand Null
relation and from the right hand
relation.
S3 N3 23 C3 3000
S4 N4 24 Null Null
S5 Null Null C5 5000
• Division Operator:
– For A/B attributes of B are subset of attributes of A.
– The relation returned by division operator will have
attributes = (All attributes of A – All Attributes of B)
– The relation returned by division operator will return those tuples from relation
A which are associated to every B’s tuple.

• Eg of Division : A/B
A B1 B2 B3
sno pno pno pno pno
s1 p1 p2 p2 p1
s1 p2 p4 p2
s1 p3 p4
s1 p4
s2 p1 A/B1 A/B2 A/B3
s2 p2
sno sno sno
s3 p2
s1 s1 s1
s4 p2
s2 s4
s4 p4 s3
s4

B2 = {S1,S2,S3,S4} ∩{S1,S4}

B3 = P1 - > {S1,S2} ∩ {S1,S2,S3,S4} ∩{S1,S4}


Aggregate Functions
• Aggregation function (ζ) takes a collection of values and
returns a single value as a result.
avg: average value
min: minimum value
max: maximum value
sum: sum of values
count: number of values
• Eg:
Name Office Dept Salary
Mithali 400 Cs 20000
Kavitha 220 Cs 45000
Sanjay 160 Econ 30000
Varun 420 Econ 55000
Asha 500 Fin 65000
1. Find the minimum salary: ζmin(salary)EMP Min(Salary)
20000

2. Find the maximum salary: ζmax(salary)EMP Max(Salary)


65000
3. Find the average salary: ζavg(salary)EMP
Avg(Salary)
43000

4. Count the no. of employees in the cs dept: ζcount(name)


Count(name)
(σdept=‘Cs’(EMP))
2

5. Find the total payroll for the economics dept:


ζsum(salary)(σdept=‘Econ’(EMP)) Sum(Salary)
85000
ER diagram to Relational mapping
name

Conceptual PRODUCT BUYS PERSON

Model: price name ssn

Relational
Model:

3
4
ER diagram to Relational mapping
7-Step Process:
1. Map Regular Entity Types
2. Map Weak Entity Types
3. Map Binary 1:1 Relation Types
4. Map Binary 1:N Relationship Types.
5. Map Binary M:N Relationship Types.
6. Map Multivalued attributes.
7. Map N-ary Relationship Types.
Mapping Entity Types to Relations
• For every entity type create a relation
• Every atomic attribute of the entity type becomes a relation attribute
• For Composite attributes: include all the atomic attributes
• Derived attributes are not included
• Attributes of the entity key make up the primary key of the relation

COURSE (courseno, subject, equip)

3
6
STUDENT (studno, givenname, familyname)
Mapping Weak Entity Types to Relations
• Create a Relation S for weak entity set.
• Add all its attributes to relation S as field.
• Add the primary key of identifying entity set R to
Relation S and Declare all foreign key constraints.

• Loan ( Loan_num, amount)


• Payment(Loan_num, pay_number, paydate, payamt)
Mapping 1 to 1 Relationship
• identify the two relations correspond to the entity
types participating in the relationship.
• Place the primary key of anyone relation as the
foreign key of other relation.
Wifeid Persons( personid , name, lastname, email , wifeid )
Wife ( wifeid , name )

» Or

Personid Persons( personid , name, lastname, email )


Wife ( wifeid , name , personid)
Mapping 1 to N or N to 1 Relationship
• let T and S be the entity sets with (1:N) where S is
having total participation in the relationship
• add primary key of T into S as foreign key.
• (Primary key of 1 side to N side as foreign key)

Personid Persons( personid , name, lastname, email )


House ( Num , address, personid)
Mapping M:N Relationship
• Create a third relation containing the primary key of both entity sets and
descriptive attribute (if any)
• The Person can live or work in many countries. Also, a country can have
many people.
countryid

Name

Personid
Persons( personid , name, lastname, email,Phone )
Countries ( countryid , name, Address)
HasRelat ( hasrelatid , personid , countryid)
Mapping Multivalued attribute
• For each multivalued attribute create a new relation T.
• Add primary key of each entity set as foreign key of Relation T.
• The foreign key attribute and multivalued attribute become composite
key.
Mapping N-ary relationship
• For each N-ary relationship, create a new relation.
• New relation will contain the primary key of all the entity sets forming the
N- ary relationship
Some more example Queries
Consider the schema depositor (Cust_name, acc_number)
Borrower (cust_name, loan_number) loan(branch_name, loan_number, amount)
• Find all loans of over $1200

amount > 1200 (loan)

 Find the loan number for each loan of an amount greater


than $1200
loan_number (amount > 1200 (loan))
 Find the names of all customers who have a loan, an account, or both, from
the bank

customer_name (borrower)  customer_name (depositor)

 Find the names of all customers who have a loan and


an account at bank.

customer_name (borrower)  customer_name (depositor)


Example Queries
Consider the schema depositor (Cust_name, acc_number)
Borrower (cust_name, loan_number) loan(branch_name, loan_number, amount)

• Find the names of all customers who have a loan at the Perryridge
branch.

customer_name (branch_name=“Perryridge”
(borrower.loan_no = loan.loan_no(borrower x loan)))
• lives(person-name,street,city)
• works(person-name, company-name,salary)
• located-in(company-name,city)
• manages(person-name,manager-name)

Find the name of all employees (i.e., persons) who work for
the City Bank company (which is a specific company in the
database).
• lives(person-name, street,city)
• works(person-name, company-name, salary)
• located-in(company-name, city)
• manages(person-name,manager-name)

Find the name and city of all employees who work for City Bank.

• Similar to previous query, except we have to access the lives table


to extract the city of the employee. The join condition is the same
person name in the two tables Lives and Works.
• lives(person-name, street,city)
• works(person-name, company-name, salary)
• located-in(company-name, city)
• manages(person-name,manager-name)

• Find all persons who do not work for City Bank.


• lives(person-name, street, city)
• works(person-name, company-name, salary)
• located-in(company-name, city)
• manages(person-name,manager-name)
Find all employees who live in the same city as the company they work
for.

For this query we need to access the lives table to get city of the employee and
the located-in table to get city of the company; plus the works table to associate
employee with their company. The selection condition is then that the two cities are
the same.
Questions
• Explain select and Project operations
• Explain union, intersect and minus operations.
• Explain division operator.
• Explain join and types of join
• Write short note on Natural join with example
• Explain Types of Outer join
• List the steps to convert ER diagram to
Relational model

You might also like