5 Relational Algebra
5 Relational Algebra
Basic/Fundamental Operations:
1. Select (σ)
2. Project (∏)
3. Union (∪)
4. Set Difference (-)
5. Cartesian product (X)
6. Rename (ρ)
Derived Operations:
3. Intersection (∩)
4. Division (÷)
Lets discuss these operations one by one with the help of examples.
If you understand little bit of SQL then you can think of it as a where clause in
SQL, which is used for the same purpose.
σ Condition/Predicate(Relation/Table name)
Select Operator (σ) Example
Table: CUSTOMER
---------------
σ Customer_City="Agra" (CUSTOMER)
Output:
Table: CUSTOMER
Customer_Name Customer_City
------------- -------------
Steve Agra
Raghu Agra
Chaitanya Noida
Ajeet Delhi
Carl Delhi
Lets discuss union operator a bit more. Lets say we have two relations R1 and
R2 both have same columns and we want to select all the tuples(rows) from
these relations then we can apply the union operator on these relations.
Note: The rows (tuples) that are present in both the tables will only appear once
in the union set. In short you can say that there are no duplicates present after
the union operation.
table_name1 ∪ table_name2
Union Operator (∪) Example
Table 1: COURSE
Student_Name
------------
Aditya
Carl
Paul
Lucy
Rick
Steve
Note: As you can see there are no duplicate names present in the output even
though we had few common names in both the tables, also in the COURSE table
we had the duplicate name itself.
Lets say we have two relations R1 and R2 both have same columns and we want
to select all those tuples(rows) that are present in both the relations, then in that
case we can apply intersection operation on these two relations R1 ∩ R2.
Note: Only those rows that are present in both the tables will appear in the result
set.
table_name1 ∩ table_name2
Intersection Operator (∩) Example
Lets take the same example that we have taken above.
Table 1: COURSE
Student_Name
------------
Aditya
Steve
Paul
Lucy
table_name1 - table_name2
Set Difference (-) Example
Lets take the same tables COURSE and STUDENT that we have seen above.
Query:
Lets write a query to select those student names that are present in STUDENT
table but not present in COURSE table.
R1 X R2
Cartesian product (X) Example
Table 1: R
Col_A Col_B
----- ------
AA 100
BB 200
CC 300
Table 2: S
Col_X Col_Y
----- -----
XX 99
YY 11
ZZ 101
Query:
Lets find the cartesian product of table R and S.
R X S
Output:
Rename (ρ)
Rename (ρ) operation can be used to rename a relation or an attribute of a
relation.
Rename (ρ) Syntax:
ρ(new_relation_name, old_relation_name)
Table: CUSTOMER
ρ(CUST_NAMES, ∏(Customer_Name)(CUSTOMER))
Output:
CUST_NAMES
----------
Steve
Raghu
Chaitanya
Ajeet
Carl
Last_Name
---------
Singh
Query to display all the details of students where Last name is ‘Singh’
The symbols used for logical operators are: ∧ for AND, ∨ for OR and ┓ for NOT.
Note:
Output:
First_Name Age
---------- ----
Ajeet 30
Chaitanya 31
Carl 28