skip to content

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).

operator =
σ city = 'London' (customers)
customers
idnamecity
1MayaLondon
2GraceParis
3SamLondon
4ZoëBerlin
σ → 2 rows
idnamecity
1MayaLondon
3SamLondon
SQLSELECT * FROM customers WHERE city = 'London'
plana Filter (or Index Cond) inside a scan or join node

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.

drawn by hand · the algebra, on three made-up relations
pick an operator. each one takes the relations on the left and returns the one on the right, computed as sets the way the algebra defines them. under it: how SQL spells it, and what runs it in a postgres plan.

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.

predict the output
π city (customers) in the algebra, SELECT city FROM customers in SQL. same number of rows?
sql
-- the algebra: π city (customers)
SELECT city FROM customers;
sqldb=shop
SELECT count(*) AS rows, count(DISTINCT city) AS cities FROM customers;
output, from postgres 18.6
SELECT 1
rowsint8citiesint8
200028
(1 row)

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:

sqldb=shop
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';
output, from postgres 18.6
#1 · EXPLAIN
HashAggregate Group Key: customers.city -> Append -> Seq Scan on customers Filter: (country = 'GB'::bpchar) -> Seq Scan on customers customers_1 Filter: (country = 'FR'::bpchar)
#2 · EXPLAIN
HashSetOp Except -> Seq Scan on customers Filter: (country = 'GB'::bpchar) -> Seq Scan on customers customers_1 Filter: (country = 'FR'::bpchar)

∪ 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
drawn by hand · the algebra
the expression as a tree. leaves are tables; every node takes the relations below it and returns one. a textbook figure.

and here's what postgres does with the SQL for it:

sqldb=shop
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;
output, from postgres 18.6
SELECT 5
nametext
Aisha Moreau
Ama Jensen
Ama Silva
Ama Smith
Amelia Ahmed
(5 rows)
show =
actual rowsestimated rows
real output, postgres 18.6 (PGlite 0.5.12) · algebra
the real plan for the same expression, without the ORDER BY and LIMIT. same shape as the algebra tree: π became a HashAggregate (DISTINCT), ⋈ a Hash Join, and σ a Filter inside the scan of customers, below the join.

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.

quick check
which one is not one of Codd's original operators, but a shorthand for others?
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.