In database theory, relational algebra is a theory that uses algebraic structures for modeling data and defining queries on it with well founded semantics. The theory was introduced by Edgar F. Codd as part of his relational model of data in 1970.
The main application of relational algebra is to provide a theoretical foundation for relational databases, particularly query languages for such databases, chief among which is SQL. Relational databases store tabular data represented as relations. Queries over relational databases often likewise return tabular data represented as relations.
The main purpose of relational algebra is to define operators that transform one or more input relations to an output relation. Given that these operators accept relations as input and produce relations as output, they can be combined and used to express complex queries that transform multiple input relations (whose data are stored in the database) into a single output relation (the query results).
Unary operators accept a single relation as input. Examples include operators to filter certain attributes (columns) or tuples (rows) from an input relation. Binary operators accept two relations as input and combine them into a single output relation. For example, taking all tuples found in either relation (union), removing tuples from the first relation found in the second relation (difference), extending the tuples of the first relation with tuples in the second relation matching certain conditions, and so forth.
Contents
Introduction
A relation of arity n is a set of n‑tuples. Relational algebra operates on homogeneous sets of tuples,
S
=
{
(
s
j
1
,
s
j
2
,
.
.
.
s
j
n
)
∣
j
∈
1...
m
}
,
{\displaystyle S=\{(s_{j1},s_{j2},...s_{jn})\mid j\in 1...m\},}
where an n‑tuple is a tuple (row; index j) with n 'types of attributes' (or data domains), thus m is the number of rows of tuples in a table and n is the number of columns (and all entries in each column have the same 'type').
A relation also has a unique tuple called the header which gives each column a unique name or attribute inside the relation. Attributes are used in projections and selections.
Set operators
The relational algebra uses set union, set difference, and Cartesian product from set theory, and adds additional constraints to these operators to create new ones.
For set union and set difference, the two relations involved must be union-compatible—that is, the two relations must have the same set of attributes. Because set intersection is defined in terms of set union and set difference, the two relations involved in set intersection must also be union-compatible.
For the Cartesian product to be defined, the two relations involved must have disjoint headers (i.e. they must not have a common attribute name).
In addition, the Cartesian product is defined differently from the one in set theory, in the sense that tuples are considered to be "shallow" for the purposes of the operation. That means the Cartesian product of a set of n-tuples with a set of m-tuples yields a set of "flattened"
(
n
+
m
)
{\displaystyle (n+m)}
-tuples (whereas basic set theory would have prescribed a set of 2-tuples, each containing an n-tuple and an m-tuple). In relational algebra, the Cartesian product
R
×
S
{\displaystyle R\times S}
is defined formally as
The cardinality of the Cartesian product is the product of the cardinalities of its factors, that is, |R × S| = |R| × |S|.
Projection
A projection (Π) is a unary operation written as
Π
a
1
,
…
,
a
n
(
R
)
{\displaystyle \Pi _{a_{1},\ldots ,a_{n}}(R)}
where
a
1
,
…
,
a
n
{\displaystyle a_{1},\ldots ,a_{n}}
is a set of attribute names. The result of such projection is defined as the set that is obtained when all tuples in R are restricted to the set
{
a
1
,
…
,
a
n
}
{\displaystyle \{a_{1},\ldots ,a_{n}\}}
Selection
A selection (sometimes called a restriction in reference to E.F. Codd's 1970 paper and not, contrary to a popular belief, to avoid confusion with SQL's use of SELECT, since Codd's article predates the existence of SQL) is a unary operation that denotes a subset of a relation.
To obtain a listing of all friends or business associates in an address book, the selection might be written as
σ
isFriend = true
∨
isBusinessContact = true
(
addressBook
)
.
{\displaystyle \sigma _{{\text{isFriend = true}}\,\lor \,{\text{isBusinessContact = true}}}({\text{addressBook}}).}
The result would be a relation containing every attribute of every unique record where isFriend is true or where isBusinessContact is true.
A selection is written as
σ
a
θ
b
(
R
)
{\displaystyle \sigma _{a\theta b}(R)}
or
σ
a
Generalized selection
A generalized selection (σ) is a unary operation written as
σ
φ
(
R
)
{\displaystyle \sigma _{\varphi }(R)}
where φ is a propositional formula that consists of atoms as allowed in the normal selection and the logical operators
∧
{\displaystyle \wedge }
(and),
∨
{\displaystyle \lor }
(or) and
¬
{\displaystyle \neg }
(negation). This selection selects all those tuples in R for which φ holds.
For an example, consider the following tables where the first table gives the relation Person and the second the result of
σ
Age
≥
30
∧
Weight
≤
60
(
Person
Computer languages
In computer languages it is expected that any truth-valued expression be permitted as the selection condition rather than restricting it to be a simple comparison.
In SQL, selections are performed by using WHERE definitions in SELECT, UPDATE, and DELETE statements, but note that the selection condition can result in any of three truth values (true, false and unknown) instead of the usual two.
In SQL, general selections are performed by using WHERE definitions with AND, OR, or NOT operands in SELECT, UPDATE, and DELETE statements.
Rename
A rename is a unary operation written as
ρ
a
/
b
(
R
)
{\displaystyle \rho _{a/b}(R)}
where:
R is a relation
a and b are attribute names
b is an attribute of R
To rename the "isFriend" attribute to "isBusinessContact" in a relation,
ρ
isBusinessContact / isFriend
(
addressBook
)
{\displaystyle \rho _{\text{isBusinessContact / isFriend}}({\text{addressBook}})}
might be used.
There is also the
ρ
x
(
A
1
,
…
,
Common extensions
In practice the classical relational algebra described above is extended with various operations such as outer joins, aggregate functions and even transitive closure.
Outer joins
Whereas the result of a join (or inner join) consists of tuples formed by combining matching tuples in the two operands, an outer join contains those tuples and additionally some tuples formed by extending an unmatched tuple in one of the operands by "fill" values for each of the attributes of the other operand. Outer joins are not considered part of the classical relational algebra discussed so far.
The operators defined in this section assume the existence of a null value, ω, which we do not define, to be used for the fill values; in practice this corresponds to the NULL in SQL. In order to make subsequent selection operations on the resulting table meaningful, a semantic meaning needs to be assigned to nulls; in Codd's approach the propositional logic used by the selection is extended to a three-valued logic, although we elide those details in this article.
Three outer join operators are defined: left outer join, right outer join, and full outer join. (The word "outer" is sometimes omitted.)
The left outer join (⟕) is written as R ⟕ S where R and S are relations. The result of the left outer join is the set of all combinations of tuples in R and S that are equal on their common attribute names, in addition (loosely speaking) to tuples in R that have no matching tuples in S.
For an example consider the tables Employee and Dept and their left outer join:
In the resulting relation, tuples in S which have no common values in common attribute names with tuples in R take a null value, ω.
Since there are no tuples in Dept with a DeptName of Finance or Executive, ωs occur in the resulting relation where tuples in Employee have a DeptName of Finance or Executive.
Let r1, r2, ..., rn be the attributes of the relation R and let {(ω, ..., ω)} be the singleton
relation on the attributes that are unique to the relation S (those that are not attributes of R). Then the left outer join can be described in terms of the natural join (and hence using basic operators) as follows:
Operations for domain computations
There is nothing in relational algebra introduced so far that would allow computations on the data domains (other than evaluation of propositional expressions involving equality). For example, it is not possible using only the algebra introduced so far to write an expression that would multiply the numbers from two columns, e.g. a unit price with a quantity to obtain a total price. Practical query languages have such facilities, e.g. the SQL SELECT allows arithmetic operations to define new columns in the result SELECT unit_price * quantity AS total_price FROM t, and a similar facility is provided more explicitly by Tutorial D's EXTEND keyword. In database theory, this is called extended projection.
Furthermore, computing various functions on a column, like the summing up of its elements, is also not possible using the relational algebra introduced so far. There are five aggregate functions that are included with most relational database systems. These operations are Sum, Count, Average, Maximum and Minimum. In relational algebra the aggregation operation over a schema (A1, A2, ... An) is written as follows:
G
1
,
G
2
,
…
,
G
m
g
f
1
(
A
1
′
)
,
f
Transitive closure
Although relational algebra seems powerful enough for most practical purposes, there are some simple and natural operators on relations that cannot be expressed by relational algebra. One of them is the transitive closure of a binary relation. Given a domain D, let binary relation R be a subset of D×D. The transitive closure R+ of R is the smallest subset of D×D that contains R and satisfies the following condition:
∀
x
∀
y
∀
z
(
(
x
,
y
)
∈
R
+
∧
(
y
,
z
)
∈
R
+
⇒
(
x
,
z
)
∈
R
Use of algebraic properties for query optimization
Relational database management systems often include a query optimizer which attempts to determine the most efficient way to execute a given query. Query optimizers enumerate possible query plans, estimate their cost, and pick the plan with the lowest estimated cost. If queries are represented by operators from relational algebra, the query optimizer can enumerate possible query plans by rewriting the initial query using the algebraic properties of these operators.
Queries can be represented as a tree, where
the internal nodes are operators,
leaves are relations,
subtrees are subexpressions.
The primary goal of the query optimizer is to transform expression trees into equivalent expression trees, where the average size of the relations yielded by subexpressions in the tree is smaller than it was before the optimization. The secondary goal is to try to form common subexpressions within a single query, or if there is more than one query being evaluated at the same time, in all of those queries. The rationale behind the second goal is that it is enough to compute common subexpressions once, and the results can be used in all queries that contain that subexpression.
Here are a set of rules that can be used in such transformations.
Selection
Rules about selection operators play the most important role in query optimization. Selection is an operator that very effectively decreases the number of rows in its operand, so if the selections in an expression tree are moved towards the leaves, the internal relations (yielded by subexpressions) will likely shrink.
Selection is idempotent (multiple applications of the same selection have no additional effect beyond the first one), and commutative (the order selections are applied in has no effect on the eventual result).
σ
A
(
R
)
=
σ
A
σ
A
(
R
)
{\displaystyle \sigma _{A}(R)=\sigma _{A}\sigma _{A}(R)\,\!}
σ
A
σ
B
(
R
)
=
σ
B
σ
A
(
Projection
Projection is idempotent, so that a series of (valid) projections is equivalent to the outermost projection.
π
a
1
,
…
,
a
n
(
π
b
1
,
…
,
b
m
(
R
)
)
=
π
a
1
,
…
,
a
n
(
R
)
where
{
a
Rename
Successive renames of a variable can be collapsed into a single rename. Rename operations which have no variables in common can be arbitrarily reordered with respect to one another, which can be exploited to make successive renames adjacent so that they can be collapsed.
ρ
a
/
b
(
ρ
b
/
c
(
R
)
)
=
ρ
a
/
c
(
R
)
{\displaystyle \rho _{a/b}(\rho _{b/c}(R))=\rho _{a/c}(R)\,\!}
ρ
a
/
b
(
ρ
c
/
d
(
R
Product and union
Cartesian product is distributive over union.
(
A
×
B
)
∪
(
A
×
C
)
=
A
×
(
B
∪
C
)
{\displaystyle (A\times B)\cup (A\times C)=A\times (B\cup C)}
Implementations
The first query language to be based on Codd's algebra was Alpha, developed by Dr. Codd himself. Subsequently, ISBL was created, and this pioneering work has been acclaimed by many authorities as having shown the way to make Codd's idea into a useful language. Business System 12 was a short-lived industry-strength relational DBMS that followed the ISBL example.
In 1998 Chris Date and Hugh Darwen proposed a language called Tutorial D intended for use in teaching relational database theory, and its query language also draws on ISBL's ideas. Rel is an implementation of Tutorial D. Bmg is an implementation of relational algebra in Ruby which closely follows the principles of Tutorial D and The Third Manifesto.
Even the query language of SQL is loosely based on a relational algebra, though the operands in SQL (tables) are not exactly relations and several useful theorems about the relational algebra do not hold in the SQL counterpart (arguably to the detriment of optimisers and/or users). The SQL table model is a bag (multiset), rather than a set. For example, the expression
(
R
∪
S
)
∖
T
=
(
R
∖
T
)
∪
(
S
∖
T
)



