In relational algebra, a join is a binary operation, written as R ⋈ S {\displaystyle R\bowtie S} where R {\displaystyle R} and S {\displaystyle S} represent relations, that combines their data where they have a common attribute.

Natural join

Natural join (⨝) is a binary operator that is written as (RS) where R and S are relations. 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:[citation needed]

Employee
NameEmpIdDeptName
Employee NameEmpIdDeptNameHarry3415FinanceSally2241SalesGeorge3401FinanceHarriet2202SalesMary1257Human ResourcesDept DeptNameManagerFinanceGeorgeSalesHarrietProductionCharlesEmployeeDept NameEmpIdDeptNameManagerHarry3415FinanceGeorgeSally2241SalesHarrietGeorge3401FinanceGeorgeHarriet2202SalesHarriet
Harry3415Finance
Sally2241Sales
George3401Finance
Harriet2202Sales
Mary1257Human Resources
DeptNameManager
FinanceGeorge
SalesHarriet
ProductionCharles
NameEmpIdDeptNameManager
Harry3415FinanceGeorge
Sally2241SalesHarriet
George3401FinanceGeorge
Harriet2202SalesHarriet

Note that neither the employee named Mary nor the Production department appear in the result. Mary does not appear in the result because Mary's Department, "Human Resources", is not listed in the Dept relation and the Production department does not appear in the result because there are no tuples in the Employee relation that have "Production" as their DeptName attribute.

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 the logical AND operator. Note 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 (this is a consequence of the idempotence of the logical AND). 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. 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 these columns must be renamed before taking the natural join. Such a join is sometimes also referred to as an equijoin.

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

R ⋈ S = { r ∪ s | r ∈ R ∧ s ∈ S ∧ F u n ( r ∪ s ) } {\displaystyle R\bowtie S=\left\{r\cup s\ \vert \ r\in R\ \land \ s\in S\ \land \ {\mathit {Fun}}(r\cup s)\right\}}

where Fun(t) is a predicate that is true for a relation t (in the mathematical sense) iff t is a function (that is, t does not map any attribute to multiple values). 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 names unique to S. Furthermore, assume that the attribute names x1,...,xm are neither in R nor in S. In a first step the common attribute names in S can be renamed:

T = ρ x 1 / c 1 , … , x m / c m ( S ) = ρ x 1 / c 1 ( ρ x 2 / c 2 ( … ρ x m / c m ( S ) … ) ) {\displaystyle 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 = σ c 1 = x 1 , … , c m = x m ( R × T ) = σ c 1 = x 1 ( σ c 2 = x 2 ( … σ c m = x m ( R × T ) … ) ) {\displaystyle 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 = Π r 1 , … , r n , c 1 , … , c m , s 1 , … , s k ( P ) {\displaystyle U=\Pi _{r_{1},\ldots ,r_{n},c_{1},\ldots ,c_{m},s_{1},\ldots ,s_{k}}(P)}

θ -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 predicate CarPriceBoatPrice produces the flattened pairs of rows which satisfy the predicate. When using a condition where the attributes are equal, for example Price, then the condition may be specified as Price=Price or alternatively (Price) itself.

Car
CarModelCarPrice
Car CarModelCarPriceCarA20,000CarB30,000CarC50,000Boat BoatModelBoatPriceBoat110,000Boat240,000Boat360,000C a r ⋈ B o a t C a r P r i c e ≥ B o a t P r i c e {\displaystyle {Car\bowtie Boat \atop \scriptstyle CarPrice\geq BoatPrice}} CarModelCarPriceBoatModelBoatPriceCarA20,000Boat110,000CarB30,000Boat110,000CarC50,000Boat110,000CarC50,000Boat240,000
CarA20,000
CarB30,000
CarC50,000
BoatModelBoatPrice
Boat110,000
Boat240,000
Boat360,000
CarModelCarPriceBoatModelBoatPrice
CarA20,000Boat110,000
CarB30,000Boat110,000
CarC50,000Boat110,000
CarC50,000Boat240,000

In order to combine tuples from two relations where the combination condition is not simply the equality of shared attributes 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 R ⋈ S a θ b {\displaystyle {R\ \bowtie \ S \atop a\ \theta \ b}} or R ⋈ S a θ v {\displaystyle {R\ \bowtie \ S \atop a\ \theta \ v}} where a and b are attribute names, θ is a binary relational operator in the set {<, ≤, =, ≠, >, ≥}, υ 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 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θ 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 selection 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).

In SQL implementations, joining on a predicate is usually called an inner join, and the on keyword allows one to specify the predicate used to filter the rows. It is important to note: forming the flattened Cartesian product then filtering the rows is conceptually correct, but an implementation would use more sophisticated data structures to speed up the join query.

Semijoin

The left semijoin (⋉ and ⋊) is a joining similar to the natural join and written as R ⋉ S {\displaystyle R\ltimes S} where R {\displaystyle R} and S {\displaystyle S} are relations. The result is the set of all tuples in R {\displaystyle R} for which there is a tuple in S {\displaystyle S} that is equal on their common attribute names. The difference from a natural join is that other columns of S {\displaystyle S} do not appear. For example, consider the tables Employee and Dept and their semijoin:[citation needed]

Employee
NameEmpIdDeptName
Employee NameEmpIdDeptNameHarry3415FinanceSally2241SalesGeorge3401FinanceHarriet2202ProductionDept DeptNameManagerSalesSallyProductionHarrietEmployeeDept NameEmpIdDeptNameSally2241SalesHarriet2202Production
Harry3415Finance
Sally2241Sales
George3401Finance
Harriet2202Production
DeptNameManager
SalesSally
ProductionHarriet
NameEmpIdDeptName
Sally2241Sales
Harriet2202Production

More formally the semantics of the semijoin can be defined as follows:

R ⋉ S = { t : t ∈ R ∧ ∃ s ∈ S ( Fun ⁡ ( t ∪ s ) ) } {\displaystyle R\ltimes S=\{t:t\in R\land \exists s\in S(\operatorname {Fun} (t\cup s))\}}

where Fun ⁡ ( r ) {\displaystyle \operatorname {Fun} (r)} is as in the definition of natural join.

The semijoin can be simulated using the natural join as follows. If a 1 , … , a n {\displaystyle a_{1},\ldots ,a_{n}} are the attribute names of R {\displaystyle R}, then

R ⋉ S = Π a 1 , … , a n ( R ⋈ S ) . {\displaystyle R\ltimes S=\Pi _{a_{1},\ldots ,a_{n}}(R\bowtie S).}

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

In Codd's 1970 paper, semijoin is called restriction.

Antijoin

The antijoin (▷), written as RS where R and S are relations, is similar to the semijoin, 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.

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

Employee
NameEmpIdDeptName
Employee NameEmpIdDeptNameHarry3415FinanceSally2241SalesGeorge3401FinanceHarriet2202ProductionDept DeptNameManagerSalesSallyProductionHarrietEmployeeDept NameEmpIdDeptNameHarry3415FinanceGeorge3401Finance
Harry3415Finance
Sally2241Sales
George3401Finance
Harriet2202Production
DeptNameManager
SalesSally
ProductionHarriet
NameEmpIdDeptName
Harry3415Finance
George3401Finance

The antijoin is formally defined as follows:

RS = { t: tR ∧ ¬∃sS(Fun (ts))}

or

RS = { t: tR, there is no tuple s of S that satisfies Fun (ts)}

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

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

RS = RRS

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

In the case where the relations have the same attributes (union-compatible), antijoin is the same as minus.

Division

The division (÷) is a binary operation that is written as R ÷ S. Division is not implemented directly in SQL. 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.

Example

Completed
StudentTask
Completed StudentTaskFredDatabase1FredDatabase2FredCompiler1EugeneDatabase1EugeneCompiler1SarahDatabase1SarahDatabase2DBProject TaskDatabase1Database2Completed ÷ DBProject StudentFredSarah
FredDatabase1
FredDatabase2
FredCompiler1
EugeneDatabase1
EugeneCompiler1
SarahDatabase1
SarahDatabase2
Task
Database1
Database2
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]: tR ∧ ∀sS ( (t[a1,...,an] ∪ s) ∈ 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.

EG: First, let's pretend that "Completed" has a third attribute called "grade". It's unwanted baggage here, so we must project it off always. In fact in this step we can drop "Task" from R as well; the multiply puts it back on. T:= πStudent(R) × S // This gives us every possible desired combination, including those that don't actually exist in R, and excluding others (eg Fred | compiler1, which is not a desired combination)

T
StudentTask
T StudentTaskFredDatabase1FredDatabase2EugeneDatabase1EugeneDatabase2SarahDatabase1SarahDatabase2
FredDatabase1
FredDatabase2
EugeneDatabase1
EugeneDatabase2
SarahDatabase1
SarahDatabase2

In the next step we subtract R from T

relation:

U:= TR

In U we have the possible combinations that "could have" been in R, but weren't.

EG: Again with projections — T and R need to have identical attribute names/headers. U:= T − πStudent,Task(R) // This gives us a "what's missing" list.

T
StudentTask
T StudentTaskFredDatabase1FredDatabase2EugeneDatabase1EugeneDatabase2SarahDatabase1SarahDatabase2R a.k.a. Completed StudentTaskFredDatabase1FredDatabase2FredCompiler1EugeneDatabase1EugeneCompiler1SarahDatabase1SarahDatabase2U aka TR aka what's missing StudentTaskEugeneDatabase2
FredDatabase1
FredDatabase2
EugeneDatabase1
EugeneDatabase2
SarahDatabase1
SarahDatabase2
StudentTask
FredDatabase1
FredDatabase2
FredCompiler1
EugeneDatabase1
EugeneCompiler1
SarahDatabase1
SarahDatabase2
StudentTask
EugeneDatabase2

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) EG: Project U down to just the attribute(s) in question (Student) V:= πStudent(U)

V
Student
V StudentEugene
Eugene

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 EG: W:= πStudent(R) − V.

πStudent(R)
Student
πStudent(R) StudentFredEugeneSarahV StudentEugeneW aka (πStudent(R) − V) aka desired result StudentFredSarah
Fred
Eugene
Sarah
Student
Eugene
Student
Fred
Sarah

Notes