Relational algebra

From Wikipedia, the free encyclopedia
Jump to: navigation, search

In computer science, relational algebra is an offshoot of first-order logic and of algebra of sets concerned with operations over finitary relations, usually made more convenient to work with by identifying the components of a tuple by a name (called attribute) rather than by a numeric column index, which is what is called a relation in database terminology.

The main application of relational algebra is providing a theoretical foundation for relational databases, particularly query languages for such databases, chiefly among which is SQL.

Contents

[edit] Introduction

Relational algebra received little attention outside of pure mathematics until the publication of E.F. Codd's relational model of data in 1970. Codd proposed such an algebra as a basis for database query languages. (See section Implementations.)

Both a named and a unnamed perspective are possible for relational algebra, depending on whether the tuples are endowed with component names or not. In the unnamed perspective, a tuple is simply a member of a Cartesian product. In the named perspective, tuples are functions from a finite set U of attributes (of the relation) to a domain of values (assumed distinct from U).[1] The relational algebras obtained from the two perspectives are equivalent.[2] The typical undergraduate textbooks present only the named perspective though,[3][4] and this article follows suit.

Relational algebra is essentially equivalent in expressive power to relational calculus (and thus first-order logic); this result is known as Codd's theorem. One must be careful to avoid a mismatch that may arise between the two languages because negation, applied to a formula of the calculus, constructs a formula that may be true on an infinite set of possible tuples, while the difference operator of relational algebra always returns a finite result. To overcome these difficulties, Codd restricted the operands of relational algebra to finite relations only and also proposed restricted support for negation (NOT) and disjunction (OR). Analogous restrictions are found in many other logic-based computer languages. Codd defined the term relational completeness to refer to a language that is complete with respect to first-order predicate calculus apart from the restrictions he proposed. In practice the restrictions have no adverse effect on the applicability of his relational algebra for database purposes.

[edit] Primitive operations

As in any algebra, some operators are primitive and the others are derived in terms of the primitive ones. It is useful if the choice of primitive operators parallels the usual choice of primitive logical operators.

Five primitive operators of Codd's algebra are the selection, the projection, the Cartesian product (also called the cross product or cross join), the set union, and the set difference. Another operator, rename was not noted by Codd, but the need for it is shown by the inventors of ISBL. These six operators are fundamental in the sense that omitting any one of them causes a loss of expressive power. Many other operators have been defined in terms of these six. Among the most important are set intersection, division, and the natural join. In fact ISBL made a compelling case for replacing the Cartesian product with the natural join, of which the Cartesian product is a degenerate case.

Altogether, the operators of relational algebra have identical expressive power to that of domain relational calculus or tuple relational calculus. However, for the reasons given in section Introduction, relational algebra is less expressive than first-order predicate calculus without function symbols. Relational algebra corresponds to a subset of first-order logic, namely Horn clauses without recursion and negation.

[edit] Set operators

Although three of the six basic operators are taken from set theory, there are additional constraints that are present in their relational algebra counterparts: 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 can be defined in terms of set difference, the two relations involved in set intersection must also be union-compatible.

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 is, the Cartesian product of an n-tuple by an m-tuple has the 2-tuple "flattened" into an (n + m)-tuple. In set theory, the Cartesian product is a set of 2-tuples. More formally, R × S is defined as follows:

R × S = {(r1, r2, ..., rn, s1, s2, ..., sm) | (r1, r2, ..., rn) ∈ R, (s1, s2, ..., sm) ∈ S}

Like the Cartesian product, the cardinality of the result is the product of the cardinalities of its factors, i.e., |R × S| = |R| × |S|. In addition, for the Cartesian product to be defined, the two relations involved must have disjoint headers—that is, they must not have a common attribute name.

[edit] Projection (π)

A projection is a unary operation written as \pi_{a_1, \ldots,a_n}( R ) where 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,\ldots,a_n\}.

This specifies the specific subset of columns (attributes of each tuple) to be retrieved. To obtain the names and phone numbers from an address book, the projection might be written \pi_{contactName, contactPhoneNumber}( addressBook ). The result of that projection would be a relation which contains only the contactName and contactPhoneNumber attributes for each unique entry in addressBook.

[edit] Selection (σ)

A generalized selection is a unary operation written as \sigma_\varphi(R) where \varphi is a propositional formula that consists of atoms as allowed in the normal selection and the logical operators \and (and), \or (or) and \lnot (negation). This selection selects all those tuples in R for which \varphi holds.

To obtain a listing of all friends or business associates in an address book, the selection might be written as \sigma_{isFriend = true \or isBusinessContact = true}( addressBook ). The result would be a relation containing every attribute of every unique record where isFriend is true or where isBusinessContact is true.

[edit] Rename (ρ)

A rename is a unary operation written as \rho_{a / b}(R) where the result is identical to R except that the b attribute in all tuples is renamed to an a attribute. This is simply used to rename the attribute of a relation or the relation itself.

To rename the 'isFriend' attribute to 'isBusinessContact' in a relation, \rho_{isBusinessContact / isFriend } ( addressBook ) might be used.

[edit] Joins and join-like operators

[edit] Natural join ()

Natural join (\bowtie) is a binary operator that is written as (R \bowtie S) where R and S are relations.[5] The result of the natural join is the set of all combinations of tuples in R and S that are equal on their common attribute names. For an example consider the tables Employee and Dept and their natural join:

Employee
Name EmpId DeptName
Harry 3415 Finance
Sally 2241 Sales
George 3401 Finance
Harriet 2202 Sales
Dept
DeptName Manager
Finance George
Sales Harriet
Production Charles
Employee  \bowtie  Dept
Name EmpId DeptName Manager
Harry 3415 Finance George
Sally 2241 Sales Harriet
George 3401 Finance George
Harriet 2202 Sales Harriet

This can also be used to define composition of relations. For example, the composition of Employee and Dept is their join as shown above, projected on all but the common attribute DeptName. In category theory, the join is precisely the fiber product.

The natural join is arguably one of the most important operators since it is the relational counterpart of logical AND. Note carefully that if the same variable appears in each of two predicates that are connected by AND, then that variable stands for the same thing and both appearances must always be substituted by the same value. In particular, natural join allows the combination of relations that are associated by a foreign key. For example, in the above example a foreign key probably holds from Employee.DeptName to Dept.DeptName and then the natural join of Employee and Dept combines all employees with their departments. Note that this works because the foreign key holds between attributes with the same name. If this is not the case such as in the foreign key from Dept.manager to Employee.Name then we have to rename these columns before we take the natural join. Such a join is sometimes also referred to as an equijoin (see θ-join).

More formally the semantics of the natural join is defined as follows:

R \bowtie S = \left\{ t \cup s \ \vert \ t \in R \ \land \ s \in S \ \land \ \mathit{Fun}(t \cup s) \right\}

where Fun is a predicate that is true for a relation r if and only if r is a function. It is usually required that R and S must have at least one common attribute, but if this constraint is omitted, and R and S have no common attributes, then the natural join becomes exactly the Cartesian product.

The natural join can be simulated with Codd's primitives as follows. Assume that c1,...,cm are the attribute names common to R and S, r1,...,rn are the attribute names unique to R and s1,...,sk are the attribute unique to S. Furthermore assume that the attribute names x1,...,xm are neither in R nor in S. In a first step we can now rename the common attribute names in S:

T = \rho_{x_1/c_1,\ldots,x_m/c_m}(S) = \rho_{x_1/c_1}(\rho_{x_2/c_2}(\ldots\rho_{x_m/c_m}(S)\ldots))

Then we take the Cartesian product and select the tuples that are to be joined:

P = \sigma_{c_1=x_1,\ldots,c_m=x_m}(R \times T) = \sigma_{c_1=x_1}(\sigma_{c_2=x_2}(\ldots\sigma_{c_m=x_m}(R \times T)\ldots))

Finally we take a projection to get rid of the renamed attributes:

U = \pi_{r_1,\ldots,r_n,c_1,\ldots,c_m,s_1,\ldots,s_k}(P)

[edit] θ-join and equijoin

Consider tables Car and Boat which list models of cars and boats and their respective prices. Suppose a customer wants to buy a car and a boat, but she does not want to spend more money for the boat than for the car. The θ-join on the relation CarPriceBoatPrice produces a table with all the possible options. When using a condition where the attributes are equal, the Price the condition may be specified as Price=Price or alternatively (Price) itself.

Car
CarModel CarPrice
CarA 20,000
CarB 30,000
CarC 50,000
Boat
BoatModel BoatPrice
Boat1 10,000
Boat2 40,000
Boat3 60,000
\begin{matrix} Car \bowtie Boat \\ \scriptstyle CarPrice \geq BoatPrice \end{matrix}
CarModel CarPrice BoatModel BoatPrice
CarA 20,000 Boat1 10,000
CarB 30,000 Boat1 10,000
CarC 50,000 Boat1 10,000
CarC 50,000 Boat2 40,000

If we want to combine tuples from two relations where the combination condition is not simply the equality of shared attributes then it is convenient to have a more general form of join operator, which is the θ-join (or theta-join). The θ-join is a binary operator that is written as \begin{matrix} R\ \bowtie\ S \\ a\ \theta\ b\end{matrix} or \begin{matrix} R\ \bowtie\ S \\ a\ \theta\ v\end{matrix} where a and b are attribute names, θ is a binary relation in the set {<, ≤, =, >, ≥}, v is a value constant, and R and S are relations. The result of this operation consists of all combinations of tuples in R and S that satisfy the relation θ. The result of the θ-join is defined only if the headers of S and R are disjoint, that is, do not contain a common attribute.

The simulation of this operation in the fundamental operations is therefore as follows:

R \bowtieφ S = σφ(R × S)

In case the operator θ is the equality operator (=) then this join is also called an equijoin.

Note, however, that a computer language that supports the natural join and rename operators does not need θ-join as well, as this can be achieved by selection from the result of a natural join (which degenerates to Cartesian product when there are no shared attributes).

[edit] Semijoin (⋉)(⋊)

The left semijoin is joining similar to the natural join and written as R \ltimes S where R and S are relations.[6] The result of this semijoin is the set of all tuples in R for which there is a tuple in S that is equal on their common attribute names. For an example consider the tables Employee and Dept and their semi join:

Employee
Name EmpId DeptName
Harry 3415 Finance
Sally 2241 Sales
George 3401 Finance
Harriet 2202 Production
Dept
DeptName Manager
Sales Bob
Sales Thomas
Production Katie
Production Mark
EmployeeDept
Name EmpId DeptName
Sally 2241 Sales
Harriet 2202 Production

More formally the semantics of the semijoin is defined as follows:

R \ltimes S = { t : t \in R, s \in S, Fun (t \cup s) }

where Fun(r) is as in the definition of natural join.

The semijoin can be simulated using the natural join as follows. If a1, ..., an are the attribute names of R, then

R \ltimes S = \Pia1,..,an(R \bowtie S).

Since we can simulate the natural join with the basic operators it follows that this also holds for the semijoin.

[edit] Antijoin (▷)

The antijoin, written as R \triangleright S where R and S are relations, is similar to the natural join, but the result of an antijoin is only those tuples in R for which there is no tuple in S that is equal on their common attribute names.[7]

For an example consider the tables Employee and Dept and their antijoin:

Employee
Name EmpId DeptName
Harry 3415 Finance
Sally 2241 Sales
George 3401 Finance
Harriet 2202 Production
Dept
DeptName Manager
Sales Sally
Production Harriet
Employee \triangleright Dept
Name EmpId DeptName
Harry 3415 Finance
George 3401 Finance

The antijoin is formally defined as follows:

R \triangleright S = { t : t \in R \and \neg\existss \in S : Fun (t \cup s) }

or

R \triangleright S = { t : t \in R, there is no tuple s of S that satisfies Fun (t \cup s) }

where Fun(r) is as in the definition of natural join.

The antijoin can also be defined as the complement of the semijoin, as follows:

R \triangleright S = R − R \ltimes S

Given this, the antijoin is sometimes called the anti-semijoin, and the antijoin operator is sometimes written as semijoin symbol with a bar above it, instead of \triangleright.

[edit] Division (÷)

The division is a binary operation that is written as R ÷ S. The result consists of the restrictions of tuples in R to the attribute names unique to R, i.e., in the header of R but not in the header of S, for which it holds that all their combinations with tuples in S are present in R. For an example see the tables Completed, DBProject and their division:

Completed
Student Task
Fred Database1
Fred Database2
Fred Compiler1
Eugene Database1
Eugene Compiler1
Sarah Database1
Sarah Database2
DBProject
Task
Database1
Database2
Completed ÷ DBProject
Student
Fred
Sarah

If DBProject contains all the tasks of the Database project, then the result of the division above contains exactly the students who have completed both of the tasks in the Database project.

More formally the semantics of the division is defined as follows:

R ÷ S = { t[a1,...,an] : t \in R \wedge \foralls \in S ( (t[a1,...,an] \cup s) \in R) }

where {a1,...,an} is the set of attribute names unique to R and t[a1,...,an] is the restriction of t to this set. It is usually required that the attribute names in the header of S are a subset of those of R because otherwise the result of the operation will always be empty.

The simulation of the division with the basic operations is as follows. We assume that a1,...,an are the attribute names unique to R and b1,...,bm are the attribute names of S. In the first step we project R on its unique attribute names and construct all combinations with tuples in S:

T := πa1,...,an(R) × S

In the prior example, T would represent a table such that every Student (because Student is the unique key / attribute of the Completed table) is combined with every given Task. So Eugene, for instance, would have two rows, Eugene -> Database1 and Eugene -> Database2 in T.

In the next step we subtract R from this relation:

U := TR

Note that in U we have the possible combinations that "could have" been in R, but weren't. So if we now take the projection on the attribute names unique to R then we have the restrictions of the tuples in R for which not all combinations with tuples in S were present in R:

V := πa1,...,an(U)

So what remains to be done is take the projection of R on its unique attribute names and subtract those in V:

W := πa1,...,an(R) − V

[edit] 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.[8]

[edit] 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. Note that outer joins are not considered part of the classical relational algebra discussed insofar.[9]

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

[edit] Left outer join (⟕)

The left outer join is written as RS where R and S are relations.[10] 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:

Employee
Name EmpId DeptName
Harry 3415 Finance
Sally 2241 Sales
George 3401 Finance
Harriet 2202 Sales
Tim 1123 Executive
Dept
DeptName Manager
Sales Harriet
Production Charles
EmployeeDept
Name EmpId DeptName Manager
Harry 3415 Finance ω
Sally 2241 Sales Harriet
George 3401 Finance ω
Harriet 2202 Sales Harriet
Tim 1123 Executive ω

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 DeptName have tuples 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:

(R \bowtie S) \cup ((R - \pi_{r_1, r_2, \dots, r_n}(R \bowtie S)) \times \{(\omega, \dots \omega)\})

[edit] Right outer join (⟖)

The right outer join behaves almost identically to the left outer join, but the roles of the tables are switched.

The right outer join of relations R and S is written as RS.[11] The result of the right outer join is the set of all combinations of tuples in R and S that are equal on their common attribute names, in addition to tuples in S that have no matching tuples in R.

For example consider the tables Employee and Dept and their right outer join:

Employee
Name EmpId DeptName
Harry 3415 Finance
Sally 2241 Sales
George 3401 Finance
Harriet 2202 Sales
Tim 1123 Executive
Dept
DeptName Manager
Sales Harriet
Production Charles
EmployeeDept
Name EmpId DeptName Manager
Sally 2241 Sales Harriet
Harriet 2202 Sales Harriet
ω ω Production Charles

In the resulting relation, tuples in R which have no common values in common attribute names with tuples in S take a null value, ω.

Since there are no tuples in Employee with a DeptName of Production, ωs occur in the Name attribute of the resulting relation where tuples in DeptName had tuples of Production.

Let s1, s2, ..., sn be the attributes of the relation S and let {(ω, ..., ω)} be the singleton relation on the attributes that are unique to the relation R (those that are not attributes of S). Then, as with the left outer join, the right outer join can be simulated using the natural join as follows:

(R \bowtie S) \cup (\{(\omega, \dots, \omega)\} \times (S - \pi_{s_1, s_2, \dots, s_n}(R \bowtie S)))

[edit] Full outer join (⟗)

The outer join or full outer join in effect combines the results of the left and right outer joins.

The full outer join is written as RS where R and S are relations.[12] The result of the full outer join is the set of all combinations of tuples in R and S that are equal on their common attribute names, in addition to tuples in S that have no matching tuples in R and tuples in R that have no matching tuples in S in their common attribute names.

For an example consider the tables Employee and Dept and their full outer join:

Employee
Name EmpId DeptName
Harry 3415 Finance
Sally 2241 Sales
George 3401 Finance
Harriet 2202 Sales
Tim 1123 Executive
Dept
DeptName Manager
Sales Harriet
Production Charles
EmployeeDept
Name EmpId DeptName Manager
Harry 3415 Finance ω
Sally 2241 Sales Harriet
George 3401 Finance ω
Harriet 2202 Sales Harriet
Tim 1123 Executive ω
ω ω Production Charles

In the resulting relation, tuples in R which have no common values in common attribute names with tuples in S take a null value, ω. Tuples in S which have no common values in common attribute names with tuples in R also take a null value, ω.

The full outer join can be simulated using the left and right outer joins (and hence the natural join and set union) as follows:

RS = (RS) \cup (RS)

[edit] 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's 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.[13] In database theory, this is called extended projection.[14]:213

[edit] Aggregation

Furthermore, computing various functions on a column, like the summing up its elements, is also not possible using the relational algebra introduced insofar. 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:

G1, G2, ..., Gm g f1(A1'), f2(A2'), ..., fk(Ak') (r)

where each Aj', 1 ≤ j ≤ k, is one of the original attributes Ai, 1 ≤ i ≤ n.

The attributes preceding the g are grouping attributes, which function like a "group by" clause in SQL. Then there are an arbitrary number of aggregation functions applied to individual attributes. The operation is applied to an arbitrary relation r. The grouping attributes are optional, and if they are not supplied, the aggregation functions are applied across the entire relation to which the operation is applied.

Let's assume that we have a table named Account with three columns, namely Account_Number, Branch_Name and Balance. We wish to find the maximum balance of each branch. This is accomplished by Branch_NameGMax(Balance)(Account). To find the highest balance of all accounts regardless of branch, we could simply write GMax(Balance)(Account).

[edit] Transitive closure

Although relational algebra seems powerful enough for most practical purposes, there are some simple and natural operators on relations which 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 containing R which satifies the following condition:

\forall x \forall y \forall z \left( (x,y) \in R^+ \wedge (y,z) \in R^+ \Rightarrow (x,z) \in R^+ \right)

There is no relational algebra expression E(R) taking R as a variable argument which produces R+. This can be proved using the fact that, given a relational expression E for which it is claimed that E(R) = R+, where R is a variable, we can always find an instance r of R (and a corresponding domain d) such that E(r) ≠ r+.[15]

SQL however officially supports such fixpoint queries since 1999, and it had vendor-specific extensions in this direction well before that.

[edit] Use of algebraic properties for query optimization

Queries can be represented as a tree, where

  • the internal nodes are operators,
  • leaves are relations,
  • subtrees are subexpressions.

Our primary goal is to transform expression trees into equivalent expression trees, where the average size of the relations yielded by subexpressions in the tree are smaller than they were before the optimization. Our secondary goal is to try to form common subexpressions within a single query, or if there are more than one queries being evaluated at the same time, in all of those queries. The rationale behind that 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 we present a set of rules, that can be used in such transformations.

[edit] 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 we manage to move the selections in an expression tree towards the leaves, the internal relations (yielded by subexpressions) will likely shrink.

[edit] Basic selection properties

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

  1. \sigma_{A}(R)=\sigma_{A}\sigma_{A}(R)\,\!
  2. \sigma_{A}\sigma_{B}(R)=\sigma_{B}\sigma_{A}(R)\,\!

[edit] Breaking up selections with complex conditions

A selection whose condition is a conjunction of simpler conditions is equivalent to a sequence of selections with those same individual conditions, and selection whose condition is a disjunction is equivalent to a union of selections. These identities can be used to merge selections so that fewer selections need to be evaluated, or to split them so that the component selections may be moved or optimized separately.

  1. \sigma_{A \land B}(R)=\sigma_{A}(\sigma_{B}(R))=\sigma_{B}(\sigma_{A}(R))
  2. \sigma_{A \lor B}(R)=\sigma_{A}(R)\cup\sigma_{B}(R)

[edit] Selection and cross product

Cross product is the costliest operator to evaluate. If the input relations have N and M rows, the result will contain NM rows. Therefore it is very important to do our best to decrease the size of both operands before applying the cross product operator.

This can be effectively done, if the cross product is followed by a selection operator, e.g. \sigma_{A}(R × P). Considering the definition of join, this is the most likely case. If the cross product is not followed by a selection operator, we can try to push down a selection from higher levels of the expression tree using the other selection rules.

In the above case we break up condition A into conditions B, C and D using the split rules about complex selection conditions, so that A = B \wedge C \wedge D and B only contains attributes from R, C contains attributes only from P and D contains the part of A that contains attributes from both R and P. Note, that B, C or D are possibly empty. Then the following holds:

\sigma_{A}(R \times P) = \sigma_{B \wedge C \wedge D}(R \times P) = \sigma_{D}(\sigma_{B}(R) \times \sigma_{C}(P))

[edit] Selection and set operators

Selection is distributive over the setminus, intersection, and union operators. The following three rules are used to push selection below set operations in the expression tree. Note, that in the setminus and the intersection operators it is possible to apply the selection operator to only one of the operands after the transformation. This can make sense in cases, where one of the operands is small, and the overhead of evaluating the selection operator outweighs the benefits of using a smaller relation as an operand.

  1. \sigma_{A}(R\setminus P)=\sigma_{A}(R)\setminus \sigma_{A}(P) =\sigma_{A}(R)\setminus P
  2. \sigma_{A}(R\cup P)=\sigma_{A}(R)\cup\sigma_{A}(P)
  3. \sigma_{A}(R\cap P)=\sigma_{A}(R)\cap\sigma_{A}(P)=\sigma_{A}(R)\cap P=R\cap \sigma_{A}(P)

[edit] Selection and projection

Selection commutes with projection if and only if the fields referenced in the selection condition are a subset of the fields in the projection. Performing selection before projection may be useful if the operand is a cross product or join. In other cases, if the selection condition is relatively expensive to compute, moving selection outside the projection may reduce the number of tuples which must be tested (since projection may produce fewer tuples due to the elimination of duplicates resulting from ommitted fields).

\pi_{a_1, \ldots ,a_n}(\sigma_A( R )) = \sigma_A(\pi_{a_1, \ldots,a_n}( R ))\text{ where fields in }A \subseteq \{a_1,\ldots,a_n\}

[edit] Projection

[edit] Basic projection properties

Projection is idempotent, so that a series of (valid) projections is equivalent to the outermost projection.

\pi_{a_1, \ldots , a_n}(\pi_{b_1,\ldots , b_m}(R)) = \pi_{a_1, \ldots , a_n}(R)\text{ where }\{a_1, \ldots , a_n\} \subseteq \{b_1, \ldots , b_m\}

[edit] Projection and set operators

Projection is distributive over set union.

\pi_{a_1, \ldots, a_n}(R \cup P) = \pi_{a_1, \ldots, a_n}(R) \cup \pi_{a_1, \ldots, a_n}(P). \,

Projection does not distribute over intersection and set difference. Counterexamples are given by:

\pi_A(\{ \langle A=a, B=b \rangle \} \cap \{ \langle A=a, B=b' \rangle \}) = \emptyset
\pi_A(\{ \langle A=a, B=b \rangle \}) \cap \pi_A(\{ \langle A=a, B=b' \rangle \}) = \{ \langle A=a \rangle \}

and

\pi_A(\{ \langle A=a, B=b \rangle \} \setminus \{ \langle A=a, B=b' \rangle \}) = \{ \langle A=a \rangle \}
\pi_A(\{ \langle A=a, B=b \rangle \}) \setminus \pi_A(\{ \langle A=a, B=b' \rangle \}) = \emptyset\,,

where b is assumed to be distinct from b'.

[edit] Rename

[edit] Basic rename properties

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.

  1. \rho_{a / b}(\rho_{b / c}(R)) = \rho_{a / c}(R)\,\!
  2. \rho_{a / b}(\rho_{c / d}(R)) = \rho_{c / d}(\rho_{a / b}(R))\,\!

[edit] Rename and set operators

Rename is distributive over set difference, union, and intersection.

  1. \rho_{a / b}(R \setminus P) = \rho_{a / b}(R) \setminus \rho_{a / b}(P)
  2. \rho_{a / b}(R \cup P) = \rho_{a / b}(R) \cup \rho_{a / b}(P)
  3. \rho_{a / b}(R \cap P) = \rho_{a / b}(R) \cap \rho_{a / b}(P)

[edit] Implementations

The first query language to be based on Codd's algebra was ISBL, 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.

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) is a theorem for relational algebra on sets, but not for relational algebra on bags; for a treatment of relational algebra on bags see chapter 5 of the "Complete" textbook by Garcia-Molina, Ullman and Widom.[14]

[edit] See also

[edit] References

  1. ^ Serge Abiteboul, Richard Hull, Victor Vianu, Foundations of databases, Addison-Wesley, 1995, ISBN 0-201-53771-0, p. 29–33
  2. ^ Serge Abiteboul, Richard Hull, Victor Vianu, Foundations of databases, Addison-Wesley, 1995, ISBN 0-201-53771-0, p. 59–63 and p. 71
  3. ^ Abraham Silberschatz; Henry Korth; S. Sudarshan (2010). Database System Concepts (6th ed.). McGraw-Hill Companies,Incorporated. ISBN 978-0-07-352332-3.
  4. ^ Raghu Ramakrishnan; Johannes Gehrke (2003). Database management systems (3rd ed.). McGraw-Hill. ISBN 978-0-07-246563-1.
  5. ^ In Unicode, the bowtie symbol is (U+22C8).
  6. ^ In Unicode, the ltimes symbol is (U+22C9). The rtimes symbol is (U+22CA)
  7. ^ In Unicode, the Antijoin symbol is (U+25B7).
  8. ^ M. Tamer Özsu; Patrick Valduriez (2011). Principles of Distributed Database Systems (3rd ed.). Springer. p. 46. ISBN 978-1-4419-8833-1. http://books.google.com/books?id=TOBaLQMuNV4C&pg=PA46.
  9. ^ Patrick O'Neil; Elizabeth O'Neil (2001). Database: Principles, Programming, and Performance, Second Edition. Morgan Kaufmann. p. 120. ISBN 978-1-55860-438-4. http://books.google.com/books?id=UXh4qTpmO8QC&pg=PA120.
  10. ^ In Unicode, the Left outer join symbol is (U+27D5).
  11. ^ In Unicode, the Right outer join symbol is (U+27D6).
  12. ^ In Unicode, the Full Outer join symbol is (U+27D7).
  13. ^ C. J. Date (2011). SQL and Relational Theory: How to Write Accurate SQL Code. O'Reilly Media, Inc.. pp. 133–135. ISBN 978-1-4493-1974-8. http://books.google.com/books?id=WuZGD5tBfMwC&pg=PA133.
  14. ^ a b Hector Garcia-Molina; Jeffrey D. Ullman; Jennifer Widom (2009). Database systems: the complete book (2nd ed.). Pearson Prentice Hall. ISBN 978-0-13-187325-4.
  15. ^ Aho, Alfred V.; Jeffrey D. Ullman (1979). "Universality of data retrieval languages". Proceedings of the 6th ACM SIGACT-SIGPLAN symposium on Principles of programming languages: 110–119. doi:10.1145/567752.567763.

[edit] Further reading

Practically any academic textbook on databases has a detailed treatment of the classic relational algebra.

[edit] External links