Duration: 2 hours (Lecture: 2 hours, Lab: 2 hours)
Syllabus Topics:
Note: The syllabus marks Intersect
and Minus
with an asterisk, indicating they may not be directly supported in MySQL. Workarounds (e.g., using subqueries or joins) will be discussed.
Relational algebra is a theoretical framework for manipulating relational databases, forming the basis for SQL queries. It provides a set of operations to query and manipulate data.
Selection (σ):
σ_condition(R)
where R
is a relation (table).σ_salary > 50000(Employees)
selects employees with a salary greater than 50,000.SELECT * FROM Employees WHERE salary > 50000;
.Projection (π):
π_columns(R)
.π_name, dept_id(Employees)
retrieves unique name
and dept_id
pairs.SELECT DISTINCT name, dept_id FROM Employees;
.Union (∪):
R ∪ S
.SELECT emp_id FROM Employees_Branch1 UNION SELECT emp_id FROM Employees_Branch2;
.Intersect (∩):
Returns rows common to two tables.
Note: MySQL does not support INTERSECT
directly. Use subqueries or joins.
Example: Find employees in both Employees_Branch1
and Employees_Branch2
.
SQL Workaround:
SELECT emp_id FROM Employees_Branch1
WHERE emp_id IN (SELECT emp_id FROM Employees_Branch2);
Minus (–):
Returns rows in one table not present in another.
Note: MySQL does not support MINUS
(or EXCEPT
). Use NOT IN
or LEFT JOIN
.
Example: Find employees in Employees_Branch1
but not in Employees_Branch2
.
SQL Workaround:
SELECT emp_id FROM Employees_Branch1
WHERE emp_id NOT IN (SELECT emp_id FROM Employees_Branch2);
Cross/Cartesian Product (×):
R × S
.SELECT * FROM Employees CROSS JOIN Departments;
.Joins combine rows from two or more tables based on a related column.
Employees.dept_id = Departments.dept_id
).SELECT * FROM Employees JOIN Departments ON Employees.dept_id = Departments.dept_id;
.SELECT e.name, d.dept_name FROM Employees e INNER JOIN Departments d ON e.dept_id = d.dept_id;
.SELECT e.name, d.dept_name FROM Employees e LEFT JOIN Departments d ON e.dept_id = d.dept_id;
.SELECT e.name, d.dept_name FROM Employees e RIGHT JOIN Departments d ON e.dept_id = d.dept_id;
.UNION
of LEFT JOIN
and RIGHT JOIN
.
Example: List all employees and departments, including unmatched rows.
SQL Workaround:
(SELECT e.name, d.dept_name FROM Employees e LEFT JOIN Departments d ON e.dept_id = d.dept_id)
UNION
(SELECT e.name, d.dept_name FROM Employees e RIGHT JOIN Departments d ON e.dept_id = d.dept_id WHERE e.dept_id IS NULL);