Computer Science · Ch 9 — Structured Query Language (SQL)
Operations on Relations
Operations on Relations
Operations on relations let us combine or compare data from two tables. The textbook introduces three such operations: Union, Intersection, and Set Difference. Each of these is a binary operation — meaning it works on two tables at a time.
These operations are not free to use on any two tables. There is a strict condition: both tables must have the same number of attributes (columns), and the corresponding attributes in both tables must have the same domain (data type). In other words, the two tables must be union-compatible. If this condition is not met, the operation cannot be performed.
Here is what each operation does:
- Union – It merges all the tuples (rows) from both tables into a single result. Duplicate rows are removed automatically, so each row appears only once. Think of it as "give me everything from table A and everything from table B, but don't repeat anything."
- Intersection – It returns only those tuples that are present in both tables. If a row exists in table A and also in table B, it appears in the result. If a row is missing from either table, it is left out.
- Set Difference – It returns tuples that are in the first table but not in the second. The order matters here:
Table1 - Table2gives rows unique to Table1, whileTable2 - Table1gives rows unique to Table2.
These operations come from set theory (like in mathematics), but in SQL they are applied to tables (relations). The result of each operation is itself a new relation.
A quick summary of the three operations:
| Operation | What it returns |
|---|---|
| Union | All distinct rows from both tables |
| Intersection | Rows common to both tables |
| Set Difference | Rows in the first table but not in the second |