Data Modeling and ER Diagram Basics
Data Modeling and ER Diagram Basics
1
• Data Modelling using the Entity-Relationship(ER)
model: Using High-Level conceptual Data Models for
Database Design, A sample Database Application,
Entity types, Entity Sets, Attributes and Keys,
Relationship Types, Relationship Sets, Roles and
Structural Constraints, Weak Entity types. Refining
the ER Design, ER Diagrams, Relationship Types of
Degree Higher than two, Relational Database Design
using ER-to-Relational Mapping.
• Relational Algebra: Unary Relational Operations,
SELECT and PROJECT, Relational Algebra Operations
from Set Theory, Binary Relational Operations: JOIN
and DIVISION, Aggregate functions and Grouping
2
Sample Database Application
• Example: HOD of CSE department calls you and asks to develop the
following application
“Develop a database application to automate the process of course
registration”
• Your first task should be to have a discussion with your client i.e HOD, to
identify the requirements of the application.
– Requirements are as follows
• Department has students and faculty
• Department will offer a set of courses during each semester
• Each student in the department during course registration will be opting for courses offered by the
department
• Faculty will be handling courses
3
Example: House design plan
4
Design plan or ER diagram before actual development of the application
Course
Course
Code
USN Name Name
Opting
Student Courses
has
Handles
Offers
has Faculty
Department
ID Name
Name
5
Design plan or ER diagram before actual development of the application
Attribute
Entity
Relationship
Requirements Were
- Department has students and faculty
- Department will offer a set of courses during each semester
- Each student in the department during course registration will be
opting for courses offered by the department
- Faculty will be handling courses
6
Design plan or ER diagram before actual development of the application
Constraints
- Each semester student
should register for minimum
of 20 credits and maximum
of 30 credits
- Each faculty can handle
a maximum two courses
During each semester
Requirements Were
- Department has students and faculty
- Department will offer a set of courses during each semester
- Each student in the department during course registration will be
opting for courses offered by the department
- Faculty will be handling courses
7
What is Entity, Entity Types, Entity sets ?
8
List out the Entities which you will come across in
real world.
9
What is Entity Types, Entity sets ?
Entity Set
10
What is Attribute ?
11
What is Attribute ?
Student DOB
12
List attributes for
1. Car
2. Book
13
Different categories of attributes
…..
Composite Attribute
Multivalued Attribute
Derived Attribute
15
What is Key ?
• Key attribute is a attribute or a combination of attributes
which will uniquely identify remaining attributes of entity.
• What are the Key attributes in the following student table ?
16
What is Key ?
• Key attribute is a attribute or a combination of attributes
which will uniquely identify remaining attributes of entity.
• What are the Key attributes in the following student table ?
17
What is Key ?
• Key attribute is a attribute or a combination of attributes
which will uniquely identify remaining attributes of entity.
• What are the Key attributes in the following student table ?
18
What is Key ?
• Key attribute is a attribute or a combination of attributes
which will uniquely identify remaining attributes of entity.
• What are the Key attributes in the following student table ?
A CSE 20K
B CSE 21K
A EC 30K
B EC 27K
C CSE 22K
19
What is Key ?
• Key attribute is a attribute or a combination of attributes
which will uniquely identify remaining attributes of entity.
• What are the Key attributes in the following student table ?
A CSE 20K
B CSE 21K
A EC 30K
B EC 27K
C CSE 22K
20
What is Key ?
• Key attribute is a attribute or a combination of attributes
which will uniquely identify remaining attributes of entity.
• What are the Key attributes in the following student table ?
A EC 30K
B EC 27K
C CSE 22K
21
What is Key ?
• Key attribute is a attribute or a combination of attributes
which will uniquely identify remaining attributes of entity.
• What are the Key attributes in the following student table ?
A EC 30K
B EC 27K Note:
Before determining the Key
C CSE 22K
attribute, look at the values
present but it will
not be consistent
22
Activity To DO
Attribute Represent Employee entity
using ER diagram notation
….. Which has following attributes
- Employee ID (Key)
Composite Attribute - Name
- Address(House No., Street
name, Area name, Place)
- Mobile Number (Can have
Multivalued Attribute
more than one )
- DOB
- Age
Derived Attribute
Entity
23
Relationship Type
• A Relationship Type defines a relationship set among entities of certain
entity types.
• Example, an Faculty works_for a department, a student enrolls_for in a
course. Here, works_for and enrolls_for are called relationships.
relationship
Works_for
Faculty Department
Enrolls_for
Student Course
24
Relationship Type
• A Relationship Type defines a relationship set among entities of certain entity types.
• Example, an Faculty works_for a department, a student enrolls_for in a course. Here,
works_for and enrolls_for are called relationships.
Dr. A
CSE
Dr. B
Dr. C
ISE
Dr. D
Faculty
Department
Entity Works_for
Entity
relationship
25
Relationship Type
• A Relationship Type defines a relationship set among entities of certain entity types.
• Example, an Faculty works_for a department, a student enrolls_for in a course. Here,
works_for and enrolls are called relationships.
Avinash
DBMS
Balaji
Chandan
Java
Dinesh
Student
Course
Entity enrolls_for
Entity
relationship
26
Relationship Set
• An Relationship Set is a collection of relationships all belonging to one relationship type.
Avinash
DBMS
Balaji
Chandan
Java
Dinesh
Student
Course
Entity enrolls_for
Entity
relationship
27
Relationship
• The association among entities is called a relationship. or A
Relationship is one instance in a Relationship Set.
Avinash
DBMS
Balaji
Chandan
Java
Dinesh
Student
Course
Entity enrolls_for
Entity
relationship
28
Relationship Degree
• Binary Relationship: Degree two, two entities
are participating
Dr. A
CSE
Dr. B
Dr.C
ISE
Dr. D
Faculty
Department
Entity Works_for
Entity
relationship
29
Relationship Degree
• Ternary Relationship: Degree three, three entities are
participating
Micro Systems
Pvt. Ltd
Laptop
UNIQ systems Manufacturing
Pvt. Ltd
Supplier
Entity Desktop
Hard disk Manufacturing
Keyboard
Project
Part supplies
Entity
Entity relationship
30
Relationship Degree
• Ternary Relationship: Degree three, three entities are
participating
Micro Systems
Pvt. Ltd
Keyboard
Project
Part supplies
Entity
Entity relationship
31
Recursive Relationship
• In some cases the same entity type participates in more than once in a
relationship type in different roles.
Dr. A Supervisor
Dr. B Subordinate
Dr. C Subordinate
Faculty
Entity supervision
relationship
32
Recursive Relationship
• In some cases the same entity type participates in more than once in a
relationship type in different roles.
Subordinate
Dr. A
Supervisor
Dr. B
Dr. C
Supervisor
Principal
Faculty
Entity supervision
relationship
33
Relationship Constraints or Structural Constraints
Two Types
1. Cardinality Ratios
a. One to one (1:1)
b. One to Many (1:M)
c. Many to Many (N:M)
2. Participation Constraints
a. Total
b. Partial
34
Cardinality Ratios
• Cardinality is a constraint on a relationship specifying the number of entity
instances that a specific entity may be related to via the relationship.
One to One:
One entity from entity set A can be associated with at most one entity of
entity set B and vice versa.
35
Cardinality Ratios
• Cardinality is a constraint on a relationship specifying the number of entity
instances that a specific entity may be related to via the relationship.
One to One:
One entity from entity set A can be associated with at most one entity of
entity set B and vice versa.
Dr. A
CSE
Dr. B ISE
Faculty Department
Heads
Entity Entity
relationship
36
Cardinality Ratios
• Cardinality is a constraint on a relationship specifying the number of entity
instances that a specific entity may be related to via the relationship.
One to One:
One instance of one entity type can participate in one instance of other entity
type.
1 1
Faculty Heads Department
37
Cardinality Ratios
• Cardinality is a constraint on a relationship specifying the number of entity
instances that a specific entity may be related to via the relationship.
One to Many:
One entity from entity set A can be associated with more than one entities of entity
set B however an entity from entity set B, can be associated with at most one entity.
1 M
Entity A R Entity B
38
Cardinality Ratios
• Cardinality is a constraint on a relationship specifying the number of entity
instances that a specific entity may be related to via the relationship.
One to Many:
One entity from entity set A can be associated with more than one entities of entity
set B however an entity from entity set B, can be associated with at most one entity.
Departme 1 M
Has Student
nt
39
Cardinality Ratios
• Cardinality is a constraint on a relationship specifying the number of entity
instances that a specific entity may be related to via the relationship.
Many to Many:
One entity from A can be associated with more than one entity from B and vice versa.
N M
Entity A R Entity B
40
Cardinality Ratios
• Cardinality is a constraint on a relationship specifying the number of entity
instances that a specific entity may be related to via the relationship.
Many to Many:
One entity from A can be associated with more than one entity from B and vice versa.
41
Cardinality Ratios
• Cardinality is a constraint on a relationship specifying the number of entity
instances that a specific entity may be related to via the relationship.
Many to Many:
One entity from A can be associated with more than one entity from B and vice versa.
42
Participation Constraint
• Minimum number of relationship instance that each entity can participate
in.
• Total Participation − Each entity is involved in the relationship. Total
participation is represented by double lines.
• Partial participation − Not all entities are involved in the relationship.
Partial participation is represented by single lines.
43
Participation Constraint
• Minimum number of relationship instance that each entity can participate in.
• Total Participation − Each entity is involved in the relationship. Total participation
is represented by double lines.
• Partial participation − Not all entities are involved in the relationship. Partial
participation is represented by single lines.
44
Participation Constraint
• Minimum number of relationship instance that each entity can participate in.
• Total Participation − Each entity is involved in the relationship. Total participation
is represented by double lines.
• Partial participation − Not all entities are involved in the relationship. Partial
participation is represented by single lines.
45
Participation Constraint
• Minimum number of relationship instance that each entity can participate in.
• Total Participation − Each entity is involved in the relationship. Total participation
is represented by double lines.
• Partial participation − Not all entities are involved in the relationship. Partial
participation is represented by single lines.
46
Weak Entity
• A weak entity set is one which does not have any primary key associated
with it.
• It relies on a combination of its attributes and the primary key of a related
strong entity to create a unique identifier
• Example : Installment entity: An installment entity can only exist if a loan
entity exists.
•
47
Weak Entity
• A weak entity set is one which does not have any primary key associated
with it.
• A weak entity type normally has partial key which is the set of attributes
that can uniquely identify weak entities that are related to same owner
entity.
48
ER Diagram Symbols
Attribute
…..
Composite Attribute
Multivalued Attribute
Derived Attribute
49
ER Diagram Symbols
Relationship
Identifying Relationship
50
Unit 2:
ER diagram design for a given requirements
51
Database Design
Database design: Why do we need it ?
• Agree on structure of the database before deciding on a particular implementation
52
Database Design Process
Requirement Conceptual Logical, Physical,
Analysis Design Security etc.,
Requirement Analysis
- What is going to be stored ?
- How is it going to be used ?
- What are we going to do with the data ?
- Who should access the data ?
53
Database Design Process
Requirement Conceptual Logical, Physical,
Analysis Design Security etc.,
Conceptual Design
- A high-level description of the database.
- Sufficiently precise that technical people can understand it.
- But, not so precise that non-technical can not participate.
54
Database Design Process
Requirement Conceptual Logical, Physical,
Analysis Design Security etc.,
55
Main phases of Database Design
56
ER Diagram Symbols
Attribute
…..
Composite Attribute
Multivalued Attribute
Derived Attribute
57
ER Diagram Symbols
Relationship
Identifying Relationship
58
Activity: ER diagram
Decision: Relationship vs Empty
59
Activity: ER diagram
Decision: Relationship vs Empty
60
Activity: ER diagram
Decision: Relationship vs Empty
Question 3: What does the following ER diagram say ?
61
Activity: ER diagram design
Draw ER diagram for the following requirements
Universal Records has decided to store information about musicians who perform on its albums
(as well as other company data) in a database.
• Each musician that records at Universal has an ID(Key) and name.
• Each instrument used in songs recorded at Universal has a unique identification number
(Key) , a name and a musical key.
• Each album recorded on the Universal label has a unique identification number (Key) , a title,
a copyright date and a format.
• Each song recorded at Universal has a Song ID (Key), a title and an author.
• Each musician may play several instruments, and a given instrument may be played by
several musicians.
• Each album has a number of songs on it, but no song may appear on more than one album.
• Each song is performed by one or more musicians, and a musician may perform a number of
songs.
• Each album has exactly one musician who acts as its producer. A musician may produce
several albums, of course.
62
Each musician that records at Universal has an ID (Key) and name.
63
Each instrument used in songs recorded at Universal has a unique identification
number (Key) , a name and a musical key.
64
Each album recorded on the Universal label has a unique identification number (Key) ,
a title, a copyright date and a format.
65
Each song recorded at Universal has a Song ID (Key), a title and
an author.
66
Each musician may play several instruments, and a given instrument may be
played by several musicians.
67
Each album has a number of songs on it, but no song may appear on more
than one album.
68
Each song is performed by one or more musicians, and a musician may
perform a number of songs.
M 1
M
N
N N
69
Each album has exactly one musician who acts as its producer. A musician
may produce several albums, of course
1 M
M M 1
N
N
M
70
• An ER diagram is a pictorial representation of the
information that can be captured by a database.
Such a “picture” serves two purposes:
– It allows database professionals to describe an overall design concisely
yet accurately.
– (Most of) it can be easily transformed into the relational schema.
• The ER diagram represents the conceptual level of database
design meanwhile the relational schema (or database table) is
the logical level for the database design.
71
Converting ER diagram to Tables
• Entities and Simple Attributes
– An entity type within ER diagram is turned into a table.
– Each attribute turns into a column (attribute) in the table. The key
attribute of the entity is the primary key of the table which is usually
underlined.
USN DOB
Name
Student
Student Table
USN Name DOB
Primary
1BM14CS001 Aditya 1-1-1997
Key
1BM14CS002 Bharath 31-12-1996
72
Converting ER diagram to Tables
• Multi-Valued Attributes
USN DOB
Name
Mobile
Student
73
Converting ER diagram to Tables
• Multi-Valued Attributes USN DOB
Name
Mobile
Student
Which of the following representation of the table for Multivalued Attribute is best ?
If you have a multi-valued attribute, take the attribute and turn it into a
new entity or table of its own. Then make a 1:N relationship between
the new entity and the existing one. In simple words,
1. Create a table for the attribute.
2. Add the primary (id) column of the parent entity as a foreign key
within the new table
75
Converting ER diagram to Tables
Street Area
Name Name
Student Mobile
76
Converting ER diagram to Tables
Street Area
Name Name
Student Mobile
Student Table
USN Name DOB Street Area Place
1BM14CS001 Aditya 1-1-1997 RK Road Nagar Mandya
USN Mobile
Mobile Table 1BM14CS001 8766655433
1BM14CS002 9762255433
1BM14CS002 7066722433
77
Converting ER diagram to Tables
Street Area
Name Name
Student Table
USN Name DOB Street Area Place
1BM14CS001 Aditya 1-1-1997 RK Road Nagar Mandya
USN Mobile
Mobile Table 1BM14CS001 8766655433
1BM14CS002 9762255433
1BM14CS002 7066722433
78
Converting ER diagram to Tables
• Relationship: One-to-One
D-ID
F-ID 1
1
F-Name
D-Name
79
Converting ER diagram to Tables
• Relationship: One-to-One
D-ID
F-ID 1
1
F-Name
D-Name
80
Converting ER diagram to Tables
• Relationship: One-to-One
D-ID
F-ID 1
1
F-Name
D-Name
81
Converting ER diagram to Tables
• Relationship: One-to-One
D-ID
F-ID 1
1
F-Name
D-Name
Approach 2: Merged Relation approach
Merging two entity types and relationship into one single relation.
This may be appropriate when both participations are total
F-Name
D-Name
Approach 3: Cross-reference or relationship relation approach
83
Converting ER diagram to Tables
• Relationship: One-to-Many
USN
D-ID M
Departme 1 Student
Has
nt
D-Name
S-Name
84
Converting ER diagram to Tables
• Relationship: One-to-Many
USN
D-ID M
Departme 1 Student
Has
nt
D-Name
S-Name
Approach 1 Student Table
Department Table USN S-Name D-ID
D-ID D-Name 1BM14CS001 Akash 10
10 CSE 1BM14CS002 Bharath 10
20 ISE 1BM14CS003 Ragu 10
1BM14CS004 Mohan 20
1BM14CS005 Nikil 20
85
Converting ER diagram to Tables
• Relationship: One-to-Many
USN
D-ID M
Departme 1 Student
Has
nt
D-Name
S-Name
Approach 2 Student Table Department
Department Table USN S-Name Student Table
USN D-ID
D-ID D-Name 1BM14CS001 Akash
1BM14CS002 Bharath 1BM14CS001 10
10 CSE
1BM14CS003 Ragu 1BM14CS002 10
20 ISE
1BM14CS004 Mohan 1BM14CS003 10
1BM14CS005 Nikil 1BM14CS004 20
1BM14CS005 20
86
Converting ER diagram to Tables
• Relationship: Many-to-Many
USN C-ID
Student Enrolls_for Course
S-Name C-Name
87
Converting ER diagram to Tables
• Relationship: Many-to-Many
USN C-ID
Enrolls_for
Student Course
S-Name C-Name
88
Converting ER diagram to Tables
• Relationship: Many-to-Many
USN C-ID
Enrolls_for
Student Course
S-Name C-Name
89
Converting ER diagramPartial
to Tables
Name
Key -----
F-ID F-Name
Faculty Dependents_of
Dependent
Owner
Identifying Weak
Entity
Relationship Entity
90
Converting ER diagramPartial
to Tables
Name
Key -----
• Weak Entity
F-ID F-Name
Faculty Dependents_of
Dependent
Owner
Identifying Weak
Entity
Relationship Entity
91
Activity To Do
Convert the Following ER diagram to Database table schema
1 M
M M 1
N
N
M
92
Database
Musician Table
tables or Schema Diagram
Name Muscian-ID
Album Table
Album-ID Copyright Format Title Producer
Date ID
Song Table
Song-ID Author Title Album-ID
Performing Table
Muscian-ID Song-ID
Plays Table
Muscian-ID Instr-ID
Instrument Table
Instr-ID Name M-Key
93
Database
Musician Table
tables or Schema Diagram
Name Muscian-ID
Album Table
Album-ID Copyright Format Title Producer
Date ID
Song Table
Song-ID Author Title Album-ID
Performing Table
Muscian-ID Song-ID
Plays Table
Muscian-ID Instr-ID
Instrument Table
Instr-ID Name M-Key
94
Unit 2:
Introduction to Relational Algebra
95
Why you should Learn “Relational Algebra” ?
Relational Algebra is
• Core of Relational Query Language, Example: SQL
• Provides framework for Query implementation and optimization
• Is a mathematical language for manipulating relations.
96
Relational Algebra based on Relational Model
97
Relational Algebra based on Relational Model
Column or Attribute
98
RDBMS Architecture
Relational Database Management System (RDBMS)
99
RDBMS Architecture
Relational Database Management System (RDBMS)
100
What is an “Algebra”
• Mathematical system consisting of:
– Operands: variables or values from which new values can be
constructed.
– Operators: symbols denoting procedures that construct new values
from given values.
101
What is Relational Algebra (RA) ?
• An algebra whose operands are database tables or relations or variables
that represent relations.
• Operators are designed to do the most common things that we need to do
with relations in a database.
– The result is an algebra that can be used as a query language for relations.
Relational Algebra Operations
102
RA operates on sets!
• RDBMSs use multisets, however in relational algebra formalism we will
consider sets!
• Also: we will consider the named perspective, where every attribute must
have a unique name
– attribute order does not matter…
103
Unary Relational Operations
• Select Operation (σ sigma)
• Project Operation (∏ phi)
104
Select Operation (σ sigma)
• It selects tuples that satisfy the given predicate from a relation.
• Select written as
105
Select Operation (σ)
Select Operation (σ)
Returns all tuples which satisfy a condition
SQL:
σselection condition(R)
SELECT *
FROM Student
Student WHERE marks > 60;
Equivalent
Relational Algebra
Expression
106
Select Operation (σ)
Select Operation (σ)
Returns all tuples which satisfy a condition
SQL:
σselection condition(R)
SELECT *
FROM Student
Student WHERE marks > 60;
107
Select Operation (σ)
Select Operation (σ)
Returns all tuples which satisfy a condition
SQL:
σselection condition(R)
SELECT *
FROM Student
Student WHERE name=‘Avinash’;
108
Project Operation (∏ phi)
• It projects column(s) that satisfy a given predicate.
• Written as
Notation ∏A1,…., An (R)
• Where A1, A2 , An are attribute names of relation R.
• Duplicate rows are automatically eliminated, as relation is a
set.
109
Project Operation (∏ phi)
• Eliminates columns, then removes duplicates
SQL:
• Written as
Notation ∏A1,…., An (R) SELECT DISTINCT
dep_num
Student FROM Student;
dep_nu
m
10
20
110
Project Operation (∏ phi)
• Eliminates columns, then removes duplicates
• Written as SQL:
Notation ∏A1,…., An (R) SELECT DISTINCT
name, dep_num
Student FROM Student;
111
Note that RA Operators are Compositional!
Student
SELECT DISTINCT
name, marks
FROM Student
WHERE marks > 60;
112
Note that RA Operators are Compositional!
Student
SELECT DISTINCT
name, marks
FROM Student
WHERE marks > 60;
113
Note that RA Operators are Compositional!
Student
SELECT DISTINCT
name, marks
FROM Student
WHERE marks > 60;
114
Note that RA Operators are Compositional!
Student
SELECT DISTINCT
name, marks
FROM Student
WHERE marks > 60;
115
Question
Student
116
Question
Student
117
Question
Student
118
Question
Student
119
Question
• Consider the relational schema Schedule containing Theater name, Movie
Title and timing at which movie will be played. Time in the Schedule table
is stored in 24Hr format i.e., 6:00pm will be stored as 18:00
Schedule(Theater, MovieTitle, Time)
120
Question
• Consider the relational schema Schedule containing Theater name, Movie
Title and timing at which movie will be played. Time in the Schedule table
is stored in 24Hr format i.e., 6:00pm will be stored as 18:00
Schedule(Theater, MovieTitle, Time)
121
Database Philosophy
Won Turing
award 1981
122
Rename Operation (ρ rho)
• The rename operation allows us to rename either relation
name or attribute names or both.
• Written as
Notation
ρS(B1,…., Bn) (R) or ρS(R) or ρ(B1,…., Bn) (R)
• S is the new relation name and B1, B2….Bn are new attribute
names.
123
Rename Operation (ρ rho)
•
SQL:
The rename operation allows us to rename the either relation name or attribute names or
Student
both. SELECT
usn as Student_USN
name as Student_Name
dep_num as Department_Number
FROM Student;
124
Binary Operations
125
• The CARTESIAN PRODUCT or CROSS JOIN returns the Cartesian product of the sets of
records from the two or more joined tables.
• Notation: table1 × table2
table1 table2
ID M ID N Relational Algebra Expression
1 a 2 p table1 x table2
2 b 3 q
4 c 5 r
126
Join Operation
Written as R ⋈joincondition S
Emp_Dept Dept
127
• Join Written as R ⋈joincondition S
• JOIN operation is used to combine related records from two tables into a single
records
• A general join condition is of the form
<condition> AND <condition> AND……AND <condition>
• Where each condition is of the form Ai θ Bj , Ai is an attribute in relation R and Bj is
an attribute in relation S, Ai and Bj have same domain
– It is called a theta join, if θ is one of the comparison operators {< , > , = , ≠ , ≤ , ≥}.
– Once again, if θ is = it's called an equijoin, and
– if the equijoin is on same-named attributes it's called a natural join and written as *.
• Similarly, there are left, right, and full outer joins; written as ⟕, ⟖, and
⟗ respectively.
128
Join Operations
Join
129
Equi Join
table1 table2
num M ID N
num M ID N
1 a 2 p
2 b 2 p
2 b 3 q
4 c 5 r
Select *
From table1, table 2
Where num=id;
130
Equi Join
Select *
From table1, table 2
table1 table2 Where num=id;
num M ID N
1 a 2 p
num M ID N
2 b 3 q
2 b 2 p
4 c 5 r
result
num M ID N
2 b 2 p
131
table1 table2
Question
result
num M ID N
num M ID N
1 a 2 p
2 b 2 p
2 b 3 q
4 c 5 r
132
Natural Join
table1 table2
ID M ID N
1 a 2 p
2 b 3 q result
4 c 5 r ID M N
2 b p
133
table1 table2
Question
result
ID M ID N ID M N
1 a 2 p 2 b p
2 b 3 q
4 c 5 r
134
What will be the output of following Relational Algebra
Expression
135
What will be the output of following Relational Algebra
Expression
136
Natural Join
table1 table2
ID M ID N
1 a 2 p
2 b 3 q result
ID M N
4 c 5 r
2 b p
Natural join does not use any comparison operator. It does not
concatenate the way a Cartesian product does. We can perform a
Natural Join only if there is at least one common attribute that exists
between two relations. In addition, the attributes must have the same
name and domain. Natural join acts on those matching attributes
where the values of attributes in both the relations are same.
137
Problem to solve
Consider three tables
• SAILORS(Sal_ID, SalName, Rating, Age)
• RESERVES(Sal_ID , Boat-ID, Rdate)
• BOATS(Boat-ID, BoatName, Color)
138
Problem to solve
139
Consider three tables
Problem to solve
SAILORS(Sal_ID, SalName, Rating, Age)
RESERVES(Sal_ID , Boat-ID, Rdate)
BOATS(Boat-ID, BoatName, Color)
OUTPUT
--------
Balaji
Dinesh
140
Consider three tables
Problem to solve
SAILORS(Sal_ID, SalName, Rating, Age)
RESERVES(Sal_ID , Boat-ID, Rdate)
BOATS(Boat-ID, BoatName, Color)
Write Relational Algebra express for the following
i. Find all the names of Sailors who have reserved boat with ID 2
SELECT *
temp1 <- σBoat_ID=2 (RESERVES) FROM RESERVES
WHERE Boat_ID = 2;
temp1
141
Consider three tables
Problem to solve
SAILORS(Sal_ID, SalName, Rating, Age)
RESERVES(Sal_ID , Boat-ID, Rdate)
BOATS(Boat-ID, BoatName, Color)
Write Relational Algebra express for the following
i. Find all the names of Sailors who have reserved boat with ID 2
SELECT SAIL_ID
temp1 <- σBoat_ID=2 (RESERVES) FROM RESERVES
temp2 <- 𝞹SAL_ID(temp1) WHERE Boat_ID = 2;
temp2
142
Problem to solve
i. Find all the names of Sailors who have reserved boat with ID 2
SELECT *
temp3
FROM SAILORS
NATURAL JOIN
(SELECT SAL_ID
FROM RESERVES
WHERE Boat_ID = 2);
143
Problem to solve
i. Find all the names of Sailors who have reserved boat with ID 2
145
SAILORS(Sal_ID, SalName, Rating, Age), RESERVES(Sal_ID , Boat-ID, Rdate),
BOATS(Boat-ID, BoatName, Color)
Write Relational Algebra express for the following
ii. Find names of sailors who have reserved RED boat
OUTPUT
--------
Balaji
Dinesh
146
SAILORS(Sal_ID, SalName, Rating, Age), RESERVES(Sal_ID , Boat-ID, Rdate),
BOATS(Boat-ID, BoatName, Color)
Write Relational Algebra express for the following
ii. Find the colors of the boat reserved by Avinash
OUTPUT
--------
Red
147
Join Operations
Join
148
Left Outer Join ⟕
result <- table1 ⟕ table2
table1 table2 result
ID M ID N ID M ID N
1 a 2 p 2 b 2 P
2 b 3 q 1 a
4 c 5 r 4 c
149
Right Outer Join ⟖
result <- table1 ⟖ table2
table1 table2
result
ID M ID N
ID M ID N
1 a 2 p
2 b 2 P
2 b 3 q
3 q
4 c 5 r
5 r
150
Full Outer Join ⟗
result <- table1 ⟗ table2
table1 table2 result
ID M ID N ID M ID N
1 a 2 p 2 b 2 p
2 b 3 q 3 q
4 c 5 r 5 r
1 a
4 c
151
Relational Algebra Set Operations - semantics
For set operations to function correctly the relations R and S must be union compatible. Two
relations are union compatible if
• they have the same number of attributes
• the domain of each attribute in column order is the same in both R and S.
152
Set Operation – Union ∪
result
result <- R U S
153
Set Operation – Intersection ∩
result
result <- R ∩ S
154
Set Operation – Difference –
155
Problem to Solve: Writing Relational Algebra Expression
156
Problem to Solve: Writing Relational Algebra Expression
157
Problem to Solve: Writing Relational Algebra Expression
i. Obtain student number and student name of all students who are working on both the projects
having project number 75 and 81
result
-----------------
556 Chandan
158
Problem to Solve: Writing Relational Algebra Expression
i. Obtain student number and student name of all students who are working on both the projects
having project number 75 and 81
result
-----------------
556 Chandan
159
Problem to Solve: Writing Relational Algebra Expression
ii. Obtain student number and student name of all those students who do not work on project
numberSTUDENT
68 ASSIGNED_TO
StudNum StudName StudNu Proj
m Num
554 Avinash
554 56
555 Balaji
555 68
556 Chandan
556 75
557 Dinesh
556 81
558 Harish
557 75 result
-----------------
554 Avinash
556 Chandan
557 Dinesh
558 Harish
160
Problem to Solve: Writing Relational Algebra Expression
i. Obtain student number and student name of all those students who do not work on project
number 68 result
-----------------
554 Avinash
556 Chandan
557 Dinesh
558 Harish
161
Homework Problem : Writing Relational Algebra Expression
iii. Obtain the student number and student name of all those students who are working on
project with name “Database”
result
-----------------
555 Balaji
556 Chandan
557 Dinesh
162
Homework Problem: Writing Relational Algebra Expression
iv. Obtain student number and student name of all students other than the student with number
554 who works on atleast one project.
result
-----------------
555 Balaji
556 Chandan
557 Dinesh
163
Relational Algebra : Division Operation ÷
The division operator is used for queries which involve the ‘all’
qualifier such as
• “Which persons have a bank account at ALL the banks in the country?”
• “Which students are registered on ALL the courses given by Sonthos?”
• “Which students are registered on ALL the courses that are taught in period 1?”
• Find sailors who have reserved ALL boats
164
Relational Algebra : Division Operation ÷
The division operator takes as input two relations, called the dividend relation
(a on scheme A) and the divisor relation (b on scheme B) such that all the
attributes in B also appear in A and B is not empty. The output of the division
operation is a relation on scheme A with all the attributes common with B.
A B A÷B
165
Relational Algebra : Division Operation ÷
The division operator takes as input two relations, called the dividend relation
(a on scheme A) and the divisor relation (b on scheme B) such that all the
attributes in B also appear in A and B is not empty. The output of the division
operation is a relation on scheme A with all the attributes common with B.
A B A÷B
166
Relational Algebra : Division Operation ÷
A B A÷B
167
Relational Algebra : Division Operation ÷
Completed DBProject
Student Task Task
Feroz Database1 Database1
Feroz Database2
Database2
Feroz Compiler1
Eshwar Database1
Sara Database1
What is the Output of the following
Sara Database2
relational Algebra Expression
Eshwar Compiler1
Completed ÷ DBProject
168
Relational Algebra : Division Operation ÷
Completed DBProject Completed ÷ DBProject
Student Task Task
Feroz Database1 Student
Database1
Feroz
Feroz Database2
Database2 Sara
Feroz Compiler1
Eshwar Database1
Sara Database1
Sara Database2
Eshwar Compiler1
169
Relational Algebra : Division Operation ÷
Completed DBProject Completed ÷ DBProject
Student Task Task
F D1 Student
D1
F
F D2
D2
F C1
E D1
Is the following two relational
E C1
algebra expressions logically equivalent ?
T ← Completed ÷ DBProject
T₁ ← 𝞹Student(Completed)
T₂ ← T₁ × DBProject
T3 ← T₂ - Completed
T4 ← 𝞹Student (T3 )
T ← T₁ - T4
170
Write relational Algebra Expresion
Find all bank customers who have account in all Branches of Bommasandra
Account Branch
branch_ acct_n
cid balance branch_id branch_city
id o
1 52 8103 43101.45 51 Belgaum
Customer
cid c_name RESULT
1 Harish
c_name
2 Triveni
Harish
3 Eshwar
171
Find all bank customers who have account in all Branches in Bommasandra
BommB
branch_id
53
59
172
Find all bank customers who have account in all Branches in Bommasandra
BommB
CB
branch_id
53
59
173
Find all bank customers who have account in all Branches in Bommasandra
BommB
CB RESULT
branch_id
53 c_name
59 Harish
174
175
Query Tree Notation
• Query Tree
– An internal data structure to represent a query
– Standard technique for estimating the work involved in
executing the query, the generation of intermediate results, and
the optimization of execution
– Nodes stand for operations like selection, projection, join,
renaming, division, ….
– Leaf nodes represent base relations
– A tree gives a good visual feel of the complexity of the query
and the operations involved
– Algebraic Query Optimization consists of rewriting the query or
modifying the query tree into an equivalent tree.
176
Query Tree Notation: Example
• Write query: For every project located in ‘Surat’, list the project number,
the controlling department number, and the department manager's last
name, address, and birth date.
177
Query Tree Notation: Example
• Example: For every project located in ‘Surat’, list the project number, the
controlling department number, and the department manager's last
name, address, and birth date.
((σPlocation='Surat'(Project) ⋈Dnum=Dnumber
𝞹Pnumber, Dnum, Lname, Address, Bdate
Department) ⋈Mgr_ssn=Ssn Employee)
178
Query Tree Notation: Example
𝞹Pnumber, Dnum, Lname, Address, Bdate (
(σPlocation='Surat'(Project) ⋈Dnum=Dnumber Department) ⋈Mgr_ssn=Ssn Employee)
179
Generalized Projection 𝞹
• Extends the projection operation by allowing arithmetic
functions to be used in the projection list.
180
Generalized Projection 𝞹
• Given relation
credit-info(CustomerName, Limit, CreditBalance)
Customer-name Limit CreditBalance
Avinash 2000 500
Balaji 700 100
Chandan 1500 1000
181
Generalized Projection 𝞹
• Given relation
credit-info(CustomerName, Limit, CreditBalance)
Customer-name Limit CreditBalance
Avinash 2000 500
Balaji 700 100
Chandan 1500 1000
182
Generalized Projection 𝞹
• Another Example
Consider a relation
EMPLOYEE(EMP-ID, Salary, Deduction, Years-of-Service)
A report may be required to show:
• Net_salary = Salary – Deduction
• Bonus = 2000 * Years-of-Service
• Tax = Salary * 25%
183
Aggregate Function ℱ (script F)
• Aggregate functions return a single value, calculated from values in a column.
Useful aggregate functions:
• AVG() - Returns the average value
• COUNT() - Returns the number of rows
• MAX() - Returns the largest value
• MIN() - Returns the smallest value
• SUM() - Returns the sum
MAX_marks
-------------
100
184
Aggregate Function ℱ (script F)
ℱCOUNT usn, AVERAGE marks(Student)
COUNT_usn AVERAGE_marks
---------------------------------
5 75
185
Using Grouping with Aggregation
<grouping attribute> ℱ <aggregate function list>
• <grouping attribute> is a list of attributes of the relation specified in R and
<aggregate function list> is a list of (<function> <attribute>)
ℱ
dep_num COUNT usn, AVERAGE marks
(Student)
186
Problem to Solve: Writing Relational Algebra Expression
187
Problem to Solve: Writing Relational Algebra Expression
TRIP
SalesPersonID From To Trip-ID
504 Chennai Delhi 10
504 Bangalore Bombay 11
505 Bangalore Srinagar 12
188
Problem to Solve: Writing Relational Algebra Expression
i. Print the total trip expenses incurred by sales person with ID 504
result
--------
18000
189
Problem to Solve: Writing Relational Algebra Expression
i. Print the total trip expenses incurred by sales person with ID 504
190
Problem to Solve: Writing Relational Algebra Expression
ii. Give the trip details for the trip that exceeded Rs. 10,000/-
result
----------------------------------------
504 Chennai Delhi 10 10000
505 Bangalore Srinagar 12 15000
191
Problem to Solve: Writing Relational Algebra Expression
ii. Give the trip details for the trip that exceeded Rs. 10,000/-
result
----------------------------------------
504 Chennai Delhi 10 10000
505 Bangalore Srinagar 12 15000
192
Problem to Solve: Writing Relational Algebra Expression
iii. Print the sales person ID and Name of the sales men who took trips to Delhi
result
--------------
504 Avinash
193
Problem to Solve: Writing Relational Algebra Expression
iii. Print the sales person ID and Name of the sales men who took trips to Delhi
result
--------------
504 Avinash
194
Problem to Solve: Writing Relational Algebra Expression
195
Problem to Solve: Writing Relational Algebra Expression
See(Spectator, Title)
Liked(Spectator, Title)
• List the people who liked movies that they have not seen
196
Problem to Solve: Writing Relational Algebra Expression
• List the producers who produced a movie that does not appear in a theater.
197
Relational Algebra Operations
• Unary Operations - operate on one relation.
These include select, project and rename
operators.
• Binary Operations - operate on pairs of
relations. These include union, set difference,
intersection, division, cartesian product, join,
equality join, natural join, Left Outer join,
Right outer join and full outer join.
198
Thank You for Your Time and Attention !
Students Should read through the
-Relational algebra example queries given in the ELMARSI and NAVATHE text book in
chapter 6 of section 6.5
-Relational Model constraints and Relational database schema, Update Transactions
and Dealing with constraint violation from ELMARSI and NAVATHE text book in chapter
5 of sections 5.2 and 5.3
199