relational algebra
selection, projection, join and friends. the handful of operators every query compiles down to.
- address
- everything.execution.relational_algebra
- part
- part 9, how a query runs
- chapter
- chapter 1 of 13
- reading time
- 8 min
relational algebra is a handful of operators that each take one or two relations and return a relation: selection (σ, keep rows), projection (π, keep columns), product (×), join (⋈), union (∪), difference (−) and rename (ρ). because every answer is a relation again, they snap together into trees.
SQL says what you want. postgres turns it into a tree of these operators, and every plan node is one way of running one of them.
the picture
you know how you can put a subquery anywhere a table goes, and a join of joins of subqueries just works? that's not a feature somebody bolted on. it falls out of one rule: every operator takes tables and gives back a table.
think of a kitchen where every tool takes a tray and hands back a tray. a sieve keeps some of what's on it (selection). a knife cuts away the parts you don't need (projection). a pairing station puts things from two trays side by side (product, and join, which is a product followed by a sieve). you can chain them in any order, because what comes out of one always fits into the next. Codd wrote the tools down in his papers of the early 1970s, and they've barely changed (the relational model has why he bothered).
| id | name | city |
|---|---|---|
| 1 | Maya | London |
| 2 | Grace | Paris |
| 3 | Sam | London |
| 4 | Zoë | Berlin |
| id | name | city |
|---|---|---|
| 1 | Maya | London |
| 3 | Sam | London |
keeps the rows where the condition holds. same columns, fewer rows. in SQL it's WHERE; in a plan it's rarely a node of its own: the planner pushes it into the scan.
seven operators, and the whole of SELECT is built from them (plus grouping and sorting, which the classic algebra leaves out and SQL adds). a few are shorthand for others: a join is σ over ×, and intersection is a difference of a difference. the joins part is the long version of ⋈.
sets vs bags
here's the one place SQL and the algebra really disagree. in the algebra a relation is a set: a row is either in it or not, never twice. SQL tables and results are bags (multisets): duplicates allowed, and kept unless you remove them.
-- the algebra: π city (customers)
SELECT city FROM customers;SELECT count(*) AS rows, count(DISTINCT city) AS cities FROM customers;| rowsint8 | citiesint8 |
|---|---|
| 2000 | 28 |
the same split runs through the set operators: UNION drops duplicates (the algebra's ∪), UNION ALL keeps them (a bag union), and EXCEPT and INTERSECT have ALL versions too (UNION, INTERSECT and EXCEPT). SQL chose bags because removing duplicates costs a sort or a hash, and most of the time you don't need it. it's also why SELECT DISTINCT shows up in plans as real work:
EXPLAIN (COSTS OFF)
SELECT city FROM customers WHERE country = 'GB'
UNION
SELECT city FROM customers WHERE country = 'FR';
EXPLAIN (COSTS OFF)
SELECT city FROM customers WHERE country = 'GB'
EXCEPT
SELECT city FROM customers WHERE country = 'FR';∪ is an Append of both inputs plus a HashAggregate to drop the duplicates. − is a HashSetOp Except. both scans carry their σ inside them as a Filter.
from algebra to a plan
take "the names of paris customers who have ordered something". as algebra, read inside out:
- keep one column, as a set
- └── pair customers with their orders
- ├── keep the parisians
- │ └── customers
- └── orders
and here's what postgres does with the SQL for it:
SELECT DISTINCT c.name
FROM customers AS c
JOIN orders AS o ON o.customer_id = c.id
WHERE c.city = 'Paris'
ORDER BY c.name
LIMIT 5;| nametext |
|---|
| Aisha Moreau |
| Ama Jensen |
| Ama Silva |
| Ama Smith |
| Amelia Ahmed |
notice where the σ ended up: inside the scan of customers, so only 66 customers ever reach the join. that isn't luck. the algebra has equivalences, and "selection can move below a join when it only uses one side" is one the planner applies every time. others: joins can be reordered (⋈ is commutative and associative), projections can be pushed down, and a selection on an equality turns a product into a join. the optimizer part is mostly the planner using rules like these to generate plans, and costs to choose between them.
the other direction matters too: one operator, many implementations. ⋈ alone is a nested loop, a hash join or a merge join; σ is a filter in a seq scan or a condition in an index scan; π with DISTINCT is a HashAggregate or a Unique. the algebra says what each step computes. the plan says how.
one level deeperthe operators SQL added
the classic algebra has no grouping, no aggregates, no sorting and no NULLs. SQL needs all of them, so the "extended" algebra adds γ (grouping with aggregates), τ (sort), δ (duplicate elimination, for bag semantics) and outer joins (⟕ ⟖ ⟗), plus semi and anti joins (⋉ ▷) for EXISTS and NOT EXISTS (semi and anti joins). relational division, "customers who bought every product in a category", is the one classic operator SQL has no keyword for at all.
keylines
- every operator takes relations and returns a relation, so they nest freely.
- σ keeps rows, π keeps columns, × pairs everything, ⋈ is σ over ×.
- the algebra uses sets; SQL uses bags. DISTINCT and UNION are the set versions.
- the planner rewrites with algebraic equivalences, like pushing σ below ⋈.
- one operator, many plan nodes: the algebra says what, the plan says how.