Relational algebra

On this page 7

Relational algebra is a formal query language consisting of a small set of operations that take one or two relations (tables) as input and produce a new relation as output. Introduced by Edgar F. Codd in 1970 as part of the relational model, it is a cornerstone of database fundamentals and the mathematical basis on which relational databases evaluate queries.

Because every operation returns a relation, operations can be composed into expressions, much like arithmetic. Database systems translate SQL statements into relational algebra trees, rewrite those trees into equivalent but cheaper forms, and then execute them. Understanding relational algebra therefore explains both what a query means and why the query optimizer can reorder it.

Relations, tuples and closure

Relational algebra operates on relations, which are sets of tuples that share the same set of named attributes, called the relation schema. In the pure theory, a relation is a set, so it contains no duplicate tuples and has no inherent row order. SQL tables differ on this point, because they are multisets (bags) that may contain duplicates unless DISTINCT is applied.

The defining property of the algebra is closure: the output of every operation is again a relation, so it can feed any other operation. This allows complex questions to be expressed as nested expressions such as a projection over a selection over a join, and it lets an optimizer treat a query as a tree of operators with base tables at the leaves.

Core operations of relational algebra

Codd’s algebra rests on a handful of primitive operations, and all others can be derived from them. The table below summarizes the primitives, their usual symbols and their closest SQL counterparts.

OperationSymbolWhat it doesSQL counterpart
Selectionσ (sigma)Keeps tuples that satisfy a predicateWHERE clause
Projectionπ (pi)Keeps chosen attributes, removes duplicatesSELECT DISTINCT column list
Union∪Combines tuples from two compatible relationsUNION
Set difference−Tuples in the first relation but not the secondEXCEPT
Cartesian product×Pairs every tuple of one relation with every tuple of anotherCROSS JOIN
Renameρ (rho)Renames a relation or its attributesAS alias
Primitive operations and their SQL equivalents

Union and difference require union-compatible inputs: both relations must have the same number of attributes with matching domains. Selection and projection are unary operations, while union, difference and product are binary operations.

Derived operations and joins

Several frequently used operations are derived from the primitives and exist mainly for convenience and efficiency. The most important is the join, which is logically a Cartesian product followed by a selection, but which database engines implement with dedicated algorithms such as nested loop, hash and sort-merge joins.

OperationDefinition in primitivesTypical use
Theta joinSelection over a Cartesian productJoins on any comparison condition
EquijoinTheta join using only equalityMatching a foreign key to a primary key
Natural joinEquijoin on same-named attributes, then projectionConcise joins on shared columns
IntersectionR − (R − S)Tuples present in both relations
DivisionCombination of product, difference and projectionQueries of the form “for all”
SemijoinJoin projected onto the left attributesEXISTS subqueries and distributed queries
Common derived operations

Classical relational algebra has no notion of missing values, so outer joins, aggregation and grouping belong to extended relational algebra. Extended operators such as the grouping operator γ cover GROUP BY and aggregate functions, and a bag semantics variant models duplicates the way SQL does.

Relational algebra in query processing

In practice, relational algebra is the internal language of the query optimizer. After parsing, a DBMS converts a SQL statement into a logical plan expressed as algebra operators, applies equivalence rules to produce alternative plans, estimates their costs from statistics, and chooses a physical plan with concrete algorithms and access paths.

The rewrite rules rely on algebraic equivalences that hold regardless of the data. The table below lists several rules that optimizers apply routinely and the benefit each one brings.

Rewrite ruleEffectBenefit
Selection pushdownApplies filters before joinsFewer tuples enter expensive operations
Projection pushdownDrops unused attributes earlyLess memory and input or output
Join commutativityR join S equals S join RAllows choosing the cheaper build side
Join associativityRegroups a sequence of joinsEnables better join orders
Cascade of selectionsSplits a conjunctive predicateEach part can be pushed separately
Equivalence rules used by optimizers

Join ordering is the hardest part: the number of possible orders grows factorially with the number of tables, so optimizers use dynamic programming for small queries and heuristics beyond roughly 10 to 15 joined tables. Poor cardinality estimates remain the most common cause of slow plans.

Relational algebra compared with relational calculus and SQL

Relational algebra is procedural: an expression describes a sequence of operations that compute the answer. Relational calculus, in its tuple and domain forms, is declarative and describes only the properties of the desired result. Codd’s theorem shows that relational algebra and safe relational calculus have the same expressive power, a property known as relational completeness.

  • SQL is declarative on the surface, closer to tuple calculus, yet it is executed through algebra plans.
  • SQL exceeds classical algebra with duplicates, NULL values, ordering, aggregation and recursive common table expressions.
  • Classical algebra cannot express transitive closure, such as finding all ancestors in a hierarchy, without recursion extensions.
  • ORDER BY has no algebraic equivalent in the set-based model, because relations are unordered.

A frequent misconception equates projection with the SQL SELECT list. Projection removes duplicates, whereas a plain SELECT keeps them; only SELECT DISTINCT matches the set-based operator exactly.

Stripped to the essentials

Relational algebra is a small toolbox of moves for working with tables. One move keeps only the rows you want, another keeps only certain columns, another glues two tables together by a shared value. Each move produces a new table, so you can chain moves like steps in a recipe.

Every database that speaks SQL quietly turns your question into these moves. The algebra is the grammar behind every query, and it lets the database rearrange the steps to reach the same answer faster.

Where it is applied

A data engineer at a regional retailer investigates a report query that joins orders, customers and stores and then filters for orders from the last 30 days in one region. The execution plan shows the database reading 40 million order rows before filtering, which takes about 90 seconds.

Reading the plan as a relational algebra tree, the engineer sees that a function wrapped around the date column prevents the optimizer from pushing the selection below the join. After rewriting the predicate as a plain range comparison, the optimizer applies selection pushdown, uses the date index and joins only about 400,000 rows. The same query now finishes in under two seconds, with an identical result set.