RA Queries
RA Queries
Some of the most common operations are Cartesian Product, Projection, Union, Intersection,
and Difference. Below is an explanation of each of these operations with examples:
The Cartesian Product (also known as Cross Join) of two relations produces all possible pairs of
rows between two tables. Each row in the first table is combined with every row in the second table.
Syntax:
Where:
Example:
Table 1: Employees
Emp_ID Name
1 John
2 Alice
3 Bob
Table 2: Departments
Dept_ID Dept_Name
101 HR
102 IT
Result:
1 John 101 HR
1 John 102 IT
2 Alice 101 HR
Emp_ID Name Dept_ID Dept_Name
2 Alice 102 IT
3 Bob 101 HR
3 Bob 102 IT
Each row from the Employees table is combined with each row from the Departments table.
2. Projection (π)
Projection selects specific columns from a relation and eliminates duplicates. It is used to retrieve
specific attributes from a table.
Syntax:
Where:
• attribute1, attribute2, ... are the attributes (columns) you want to keep.
Example:
1 John 50000 HR
2 Alice 60000 IT
3 Bob 55000 IT
Result:
Name Salary
John 50000
Alice 60000
Bob 55000
Only the Name and Salary columns are returned, with duplicates removed.
3. Union (∪)
Union combines the results of two relations and returns all unique rows that appear in either of the
two relations. The two relations must have the same schema (same number and type of columns).
Syntax:
Where:
Example:
Table 1: Employees
Emp_ID Name
1 John
2 Alice
Table 2: Contractors
Emp_ID Name
3 Bob
4 Carol
Result:
Emp_ID Name
1 John
2 Alice
3 Bob
4 Carol
All rows from both tables are returned, with duplicates removed.
4. Intersection (∩)
Intersection returns the rows that are common to both relations. The two relations must have the
same schema.
Syntax:
Where:
Example:
Table 1: Employees
Emp_ID Name
1 John
2 Alice
3 Bob
Table 2: Contractors
Emp_ID Name
2 Alice
3 Bob
4 Carol
Result:
Emp_ID Name
2 Alice
3 Bob
Only the rows that appear in both tables are returned.
5. Difference (−)
Difference returns the rows that appear in the first relation but not in the second relation. The two
relations must have the same schema.
Syntax:
R1−R2R_1 - R_2R1−R2
Where:
Example:
Table 1: Employees
Emp_ID Name
1 John
2 Alice
3 Bob
Table 2: Contractors
Emp_ID Name
2 Alice
3 Bob
4 Carol
Employees−Contractors\text{Employees} - \text{Contractors}Employees−Contractors
Result:
Emp_ID Name
1 John
The rows in Employees that are not present in Contractors are returned. In this case, only the row
for "John" is returned.
Summary of Operations:
Operation Description
Cartesian Product (×) Combines each row from one table with every row of another table.
Difference (−) Returns rows in the first table that are not in the second table.