1. Home
  2. Explore
  3. Computer Science
  4. Relational Algebra

Study methods

Flashcards
Quiz
Fill in the blanks
Written test
Lesson
Notes
Podcast
Content

Relational Algebra

Relational Algebra: A Tutor-Guided Lesson

Relational algebra is the formal language used to manipulate data in a relational database. It provides a systematic way to retrieve, combine, filter, and reorganize information stored in relations.

A relational algebra expression does not merely state what data is wanted. It also describes how the database should obtain that data. For this reason, relational algebra is called a procedural query language.

Relational algebra is a procedural language consisting of operations that take one or two relations as input and produce a new relation as output.

A relation is usually represented as a table. Therefore, relational algebra operations behave like carefully defined transformations on tables. Several operations can be combined into one expression, allowing complex queries to be built from simpler steps.


1. Foundations of Relational Algebra

Before studying the operations, several basic terms must be understood.

Relations, tuples, and attributes

A relation is a collection of tuples. In a database, a relation corresponds to a table.

A tuple is an ordered sequence of values. In a database, a tuple corresponds to a row.

An attribute is a field or column in a relation. For example, a relation named Actors might contain the attributes ID, FirstName, LastName, and Gender.

A domain is the set of permitted values for an attribute. For example:

  • An ID attribute may use integer values.
  • A FirstName attribute may use character strings.
  • A Gender attribute may use values from a defined set of allowed categories.

The degree of a relation is the number of attributes it contains. A relation with four columns has degree 444.

Operands and operators

Relational algebra has two main components:

  • Operands: relations or variables representing relations.
  • Operators: symbols or commands that transform relations.

For example, in the expression

R∪SR \cup SR∪S

RRR and SSS are operands, while ∪\cup∪ is the operator.

Every valid operation produces another relation. This is important because the result of one operation can become the input to a later operation. This property makes it possible to combine operations into complex expressions.

Union compatibility

Some relational algebra operations require two relations to be union-compatible.

Two relations are union-compatible when:

  1. They have the same degree, meaning they contain the same number of attributes.
  2. Corresponding attributes come from compatible domains.

For example, if one relation has the attributes ID, FirstName, LastName, and Type, a second relation must also have four corresponding attributes whose values are compatible. The attribute names may sometimes be adjusted through renaming, but the positions and data types must be compatible.

Union compatibility is required for:

  • Union
  • Intersection
  • Set difference

It is not required for the Cartesian product.


2. The Four Main Categories of Operations

Relational algebra operations can be grouped into four categories:

  1. Set operations: operate on two relations using ideas from mathematical set theory.
  2. Unary operations: use one relation as input.
  3. Binary operations: combine two relations into one relation.
  4. Extended operations: add capabilities beyond the basic operations.

The set operations and binary operations both use two input relations, while unary operations use only one.


3. Set Operations

Set operations are based on standard mathematical operations applied to relations. Since they operate on two relations, they are binary operations.

The four set operations are:

  • Union
  • Intersection
  • Set difference
  • Cartesian product

For union, intersection, and set difference, the two relations must be union-compatible.


3.1 Union

The union of two relations returns every tuple that appears in either relation.

It is written as:

R∪SR \cup SR∪S

The result contains:

  • All tuples from RRR
  • All tuples from SSS
  • No duplicate tuples

If RRR and SSS have degree nnn, then R∪SR \cup SR∪S also has degree nnn.

For example, suppose Writers and Clients are union-compatible. The expression

Writers∪ClientsWriters \cup ClientsWriters∪Clients

returns every tuple appearing in either relation. If a tuple, such as a record for John Cena, appears in both relations, it appears only once in the result.

Union is useful when two tables represent similar kinds of information and the desired result should include records from both.

Key properties of union

  • The operands must be union-compatible.
  • The result has the same degree as the operands.
  • Duplicate tuples are removed.
  • The operation is not affected by the order of the relations:
R∪S=S∪RR \cup S = S \cup RR∪S=S∪R

3.2 Intersection

The intersection of two relations returns only the tuples that appear in both relations.

It is written as:

R∩SR \cap SR∩S

For example:

Writers∩ClientsWriters \cap ClientsWriters∩Clients

returns the records that belong to both Writers and Clients.

If John Cena is the only tuple appearing in both relations, the result contains only John Cena. Any tuple appearing in just one of the relations is excluded.

Key properties of intersection

  • The operands must be union-compatible.
  • The result has the same degree as the operands.
  • Duplicate tuples are removed.
  • Only common tuples are returned.
  • The order of the operands does not affect the result:
R∩S=S∩RR \cap S = S \cap RR∩S=S∩R

Intersection is useful when a query asks for records satisfying membership in two groups simultaneously.


3.3 Set Difference

The set difference operation returns the tuples that belong to the first relation but do not belong to the second relation.

It is written as:

R−SR - SR−S

The order of the operands is important.

For example:

Writers−ClientsWriters - ClientsWriters−Clients

returns tuples found in Writers but not in Clients.

If John Cena appears in both relations, John Cena is removed from the result. If Mary, Harold, and Joy appear in Clients but not in Writers, then:

Clients−WritersClients - WritersClients−Writers

returns those tuples.

The two expressions generally produce different results:

R−S≠S−RR - S \neq S - RR−S=S−R

Key properties of set difference

  • The operands must be union-compatible.
  • The result has the same degree as the operands.
  • Duplicate tuples are removed.
  • The first relation defines the starting set.
  • Reversing the operands changes the meaning and usually changes the result.

A useful way to interpret R−SR-SR−S is: “Keep everything in RRR, except anything also found in SSS.”


3.4 Cartesian Product

The Cartesian product combines every tuple in one relation with every tuple in the other relation.

It is written as:

R×SR \times SR×S

Each tuple in RRR is paired with every tuple in SSS.

If relation RRR contains mmm tuples and relation SSS contains nnn tuples, the result contains:

m×nm \times nm×n

tuples.

If RRR has degree 444 and SSS has degree 444, the result has degree:

4+4=84+4=84+4=8

The attributes of the paired tuples are concatenated into one larger tuple.

For example, if Writers and Clients each contain four attributes, then:

Writers×ClientsWriters \times ClientsWriters×Clients

pairs every writer with every client and produces tuples with eight attributes.

Unlike union, intersection, and set difference, the Cartesian product does not require union compatibility. The two relations may have different numbers of attributes and different domains.

Cartesian products are especially useful as an intermediate step in join operations. However, because the result can become very large, a Cartesian product is usually combined with a condition to keep only meaningful pairs.

Example of size

If Writers contains 555 tuples and Clients contains 444 tuples, then:

∣Writers×Clients∣=5×4=20|Writers \times Clients|=5 \times 4=20∣Writers×Clients∣=5×4=20

tuples are produced.

A Cartesian product pairs every tuple in the first relation with every tuple in the second relation.

Think About It

A student examining R−SR-SR−S should ask: “Which relation supplies the records being kept?” This identifies why swapping the operands changes the result. For R×SR \times SR×S, the key question is: “How many pairings are possible if every tuple must meet every tuple from the other relation?”


4. Unary Operations

A unary operation takes one relation as input and produces one relation as output.

The four unary operations discussed here are:

  • Selection
  • Projection
  • Rename
  • Assignment

Unary operations are often used before set operations or joins to prepare relations for combination.


4.1 Selection

The selection operation returns only the rows that satisfy a specified condition. It is therefore a horizontal filter.

Selection is written using the Greek letter sigma:

σcondition(R)\sigma_{\text{condition}}(R)σcondition​(R)

The condition may use comparison operators and logical operators such as:

  • Equal to
  • Not equal to
  • Less than
  • Greater than
  • Less than or equal to
  • Greater than or equal to
  • AND
  • OR
  • Pattern matching such as LIKE

For example, to select actors whose last name ends with a particular pattern:

σLastName LIKE pattern(Actors)\sigma_{\text{LastName LIKE pattern}}(Actors)σLastName LIKE pattern​(Actors)

To retrieve movies released in 200320032003 with a rank greater than 777:

σYear=2003 AND Rank>7(Movies)\sigma_{\text{Year}=2003 \ \text{AND}\ \text{Rank}>7}(Movies)σYear=2003 AND Rank>7​(Movies)

The operation keeps the original columns but removes rows that fail the condition.

Selection as a horizontal filter

If a table has ten columns and selection is applied, the result may still have all ten columns. The difference is that only qualifying rows remain.

This contrasts with projection, which filters columns rather than rows.


4.2 Projection

The projection operation returns selected columns from a relation. It is therefore a vertical filter.

Projection is written using the Greek letter pi:

πattribute list(R)\pi_{\text{attribute list}}(R)πattribute list​(R)

For example, to retrieve only the first names of actors:

πFirstName(Actors)\pi_{\text{FirstName}}(Actors)πFirstName​(Actors)

To retrieve both first and last names:

πFirstName, LastName(Actors)\pi_{\text{FirstName, LastName}}(Actors)πFirstName, LastName​(Actors)

Projection removes attributes that are not listed. Duplicate resulting tuples are eliminated because a relation is treated as a set.

Combining selection and projection

Suppose the goal is to find the first and last names of actors whose first name is Michael. The query can be performed in two stages:

First, select the qualifying actors:

σFirstName=Michael(Actors)\sigma_{\text{FirstName}=\text{Michael}}(Actors)σFirstName=Michael​(Actors)

Then project the desired attributes:

πFirstName, LastName(σFirstName=Michael(Actors))\pi_{\text{FirstName, LastName}} \left( \sigma_{\text{FirstName}=\text{Michael}}(Actors) \right)πFirstName, LastName​(σFirstName=Michael​(Actors))

The order matters conceptually:

  1. Selection identifies the correct rows.
  2. Projection retains only the required columns.

Selection versus projection

OperationSymbolFiltersMain effect
Selectionσ\sigmaσRowsKeeps tuples satisfying a condition
Projectionπ\piπColumnsKeeps specified attributes

Selection answers “Which rows?” Projection answers “Which columns?”


4.3 Rename

The rename operation changes the name of a relation, its attributes, or both. Rename is useful when:

  • A relation needs a clearer temporary name.
  • Two relations have conflicting attribute names.
  • Attributes must be made compatible before a set operation.
  • A query refers to the same relation more than once.

Renaming a relation can be represented as:

ρNewRelationName(R)\rho_{\text{NewRelationName}}(R)ρNewRelationName​(R)

Renaming attributes can be represented conceptually as:

ρNewAttributeList(R)\rho_{\text{NewAttributeList}}(R)ρNewAttributeList​(R)

Renaming both the relation and its attributes can be represented as:

ρNewRelationName(NewAttributeList)(R)\rho_{\text{NewRelationName}(\text{NewAttributeList})}(R)ρNewRelationName(NewAttributeList)​(R)

For example, renaming Directors to Producers gives:

ρProducers(Directors)\rho_{\text{Producers}}(Directors)ρProducers​(Directors)

An attribute list might rename ID, FirstName, and LastName to DirectorID, FName, and LName.

Rename does not change the actual tuples. It changes the labels used to identify the relation or its attributes.

Why rename matters for compatibility

Suppose Actors and Directors contain similar information but use different attribute names. A projection can first select matching attributes, and rename can then give them compatible names. After these changes, a union may become valid.

This illustrates a general strategy:

  1. Use selection to restrict rows.
  2. Use projection to choose columns.
  3. Use rename to make relation structures compatible.
  4. Apply a set operation.

4.4 Assignment

The assignment operation stores the result of an expression in a temporary relation variable.

It is written conceptually as:

T←ET \leftarrow ET←E

where TTT is the temporary relation and EEE is a relational algebra expression.

Assignment is useful for complex queries because it allows the query to be written as a sequence of smaller steps.

For example, the first step might select male actors:

MaleActors←σGender=M(Actors)MaleActors \leftarrow \sigma_{\text{Gender}=\text{M}}(Actors)MaleActors←σGender=M​(Actors)

The temporary relation MaleActors can then be used in another operation.

Another example begins by combining two relations:

T←Actors×MovieGenresT \leftarrow Actors \times MovieGenresT←Actors×MovieGenres

A later expression can filter the temporary relation:

σGenre=Action(T)\sigma_{\text{Genre}=\text{Action}}(T)σGenre=Action​(T)

Assignment makes a relational algebra query resemble a short sequential program:

  1. Calculate an intermediate relation.
  2. Give it a temporary name.
  3. Use that name in the next step.
  4. Display the final expression’s result.

This is especially helpful when a single expression would become difficult to read.

Think About It

A student can distinguish the unary operations by asking four questions:

  • Which rows satisfy the condition? — selection.
  • Which columns are needed? — projection.
  • What should the relation or columns be called? — rename.
  • Should an intermediate result be saved for later use? — assignment.

5. Binary Operations

A binary operation combines two input relations into one output relation.

The binary operations discussed are:

  • Theta join
  • Equijoin
  • Natural join
  • Division

Joins are important because useful information is often distributed across multiple related tables.


5.1 Theta Join

A theta join, also called a conditional join, joins two relations according to a specified comparison condition.

It may use comparison operators such as:

=, ≠, <, >, ≤, ≥=,\ \neq,\ <,\ >,\ \leq,\ \geq=, =, <, >, ≤, ≥

A theta join can be represented as:

R⋈θSR \bowtie_{\theta} SR⋈θ​S

where θ\thetaθ is the join condition.

For example, to match PCs with laptops whose speeds are related by a less-than condition:

PC⋈PC.Speed<Laptop.SpeedLaptopPC \bowtie_{\text{PC.Speed}<\text{Laptop.Speed}} LaptopPC⋈PC.Speed<Laptop.Speed​Laptop

Only pairs satisfying the condition appear in the result.

If a PC has speed 1.421.421.42 and several laptops have speeds greater than 1.421.421.42, that PC is paired with each of those laptops. If no laptop satisfies the condition for another PC, that PC contributes no tuple to the join.

A theta join can be understood as a Cartesian product followed by a selection:

R⋈θS=σθ(R×S)R \bowtie_{\theta} S = \sigma_{\theta}(R \times S)R⋈θ​S=σθ​(R×S)

The join avoids retaining meaningless pairings by applying the condition.


5.2 Equijoin

An equijoin is a special type of theta join in which the only comparison condition used is equality.

It is written conceptually as:

R⋈R.A=S.BSR \bowtie_{R.A=S.B} SR⋈R.A=S.B​S

For example:

PC⋈PC.RAM=Laptop.RAMLaptopPC \bowtie_{\text{PC.RAM}=\text{Laptop.RAM}} LaptopPC⋈PC.RAM=Laptop.RAM​Laptop

returns PC–laptop pairs whose RAM values are equal.

If a PC has 102410241024 units of RAM and a laptop also has 102410241024 units, they are included in the result. Pairs with unequal RAM values are excluded.

An equijoin may retain both copies of the matching attributes. For instance, the result may include both PC.RAM and Laptop.RAM.

Theta join versus equijoin

  • A theta join may use any comparison condition.
  • An equijoin uses equality only.
  • Every equijoin is a theta join, but not every theta join is an equijoin.

5.3 Natural Join

A natural join joins two relations using attributes that have:

  1. The same name.
  2. Compatible domains.
  3. At least one common attribute between the relations.

The natural join automatically applies equality to the common attributes and removes the duplicate copy of the common attribute.

It is written as:

R⋈SR \bowtie SR⋈S

For example, suppose Product contains Maker, Model, and other product information, while PC contains Model, Speed, RAM, and Price.

The common attribute is Model. A natural join matches rows where the model values are equal:

Product⋈PCProduct \bowtie PCProduct⋈PC

The output contains the combined information, but only one Model attribute appears.

A natural join is convenient when the database schema uses matching names consistently. If common attributes have different names, a natural join cannot automatically recognize them; projection and rename may be needed first.

Example strategy

To find the maker of each laptop:

  1. Project Maker and Model from Product:
πMaker, Model(Product)\pi_{\text{Maker, Model}}(Product)πMaker, Model​(Product)
  1. Naturally join the result with Laptop:
πMaker, Model(Product)⋈Laptop\pi_{\text{Maker, Model}}(Product) \bowtie LaptopπMaker, Model​(Product)⋈Laptop

The matching Model attribute connects the two relations, and the duplicate model column is removed.


5.4 Division

The division operation identifies tuples in one relation that are associated with every tuple in another relation.

It is written as:

R÷SR \div SR÷S

Division is useful for queries involving words such as:

  • “All”
  • “Every”
  • “Each”

Suppose a relation records laptop models and the properties they possess. Dividing by a relation containing a set of required properties returns the laptop models associated with every required property.

For example, if division is used to find laptops meeting every required speed or RAM value, only laptops satisfying all of those values are returned.

Attributes used in the dividing relation do not appear in the result. If the first relation contains Model, Price, and Speed, and division is performed using Speed, the result may contain only:

  • Model
  • Price

The Speed attribute is not included because it serves as the condition being satisfied.

Division example

Suppose a selection first identifies PCs with RAM equal to 102410241024, and projection keeps only the RAM attribute:

πRAM(σRAM=1024(PC))\pi_{\text{RAM}} \left( \sigma_{\text{RAM}=1024}(PC) \right)πRAM​(σRAM=1024​(PC))

That result can serve as the divisor:

Laptop÷πRAM(σRAM=1024(PC))Laptop \div \pi_{\text{RAM}} \left( \sigma_{\text{RAM}=1024}(PC) \right)Laptop÷πRAM​(σRAM=1024​(PC))

The result contains laptop models associated with the required RAM value. The example identifies laptop models such as 200220022002, 200520052005, 200720072007, and 200820082008.

Think About It

A student should recognize the distinction between join and division:

  • A join asks which pairs of tuples match.
  • Division asks which tuples satisfy a relationship with every tuple in another relation.

The word “every” is a strong signal that division may be appropriate.


6. Extended Operations

Extended operations add expressive power to basic relational algebra. They are useful when a query requires calculations, summaries, unmatched records, or relations with partially overlapping structures.

The extended operations discussed are:

  • Generalized projection
  • Aggregation
  • Outer join
  • Outer union

6.1 Generalized Projection

Ordinary projection selects existing attributes. Generalized projection extends projection by allowing arithmetic expressions in the projection list.

Its general form is:

πF1,F2,…,Fn(E)\pi_{F_1,F_2,\ldots,F_n}(E)πF1​,F2​,…,Fn​​(E)

where:

  • EEE is a relation algebra expression.
  • F1,F2,…,FnF_1,F_2,\ldots,F_nF1​,F2​,…,Fn​ are attributes or arithmetic expressions.

For example, suppose CreditInfo contains:

  • CustomerName
  • CreditLimit
  • CreditBalance

The amount of credit currently consumed can be calculated as:

CreditLimit−CreditBalanceCreditLimit-CreditBalanceCreditLimit−CreditBalance

A generalized projection can display the customer name and calculate a new attribute:

πCustomerName, CreditLimit−CreditBalance→CreditConsumed(CreditInfo)\pi_{\text{CustomerName},\ \text{CreditLimit}-\text{CreditBalance}\rightarrow\text{CreditConsumed}} (CreditInfo)πCustomerName, CreditLimit−CreditBalance→CreditConsumed​(CreditInfo)

The arrow indicates that the calculated result is given the name CreditConsumed.

Generalized projection is useful because it creates derived information without changing the original relation.

Another example is adding a delivery charge to each laptop’s cost:

πModel, Price+200→TotalCost(Laptop)\pi_{\text{Model},\ \text{Price}+200\rightarrow\text{TotalCost}}(Laptop)πModel, Price+200→TotalCost​(Laptop)

The resulting relation displays each model and its calculated total cost.


6.2 Aggregation

An aggregate function takes a collection of values and produces a single summary value.

The aggregate functions discussed are:

  • SUM
  • AVERAGE
  • COUNT
  • MIN
  • MAX

Aggregation is represented using a special grouping and aggregation symbol, often written as a script-style gamma:

γgrouping attributes; aggregate function(R)\gamma_{\text{grouping attributes};\ \text{aggregate function}}(R)γgrouping attributes; aggregate function​(R)

If employee salaries are stored in PropEmp and employees belong to departments, the total salary for each department can be calculated as:

γDept; SUM(Salary)→TotalDeptSalary(PropEmp)\gamma_{\text{Dept};\ \text{SUM(Salary)}\rightarrow\text{TotalDeptSalary}}(PropEmp)γDept; SUM(Salary)→TotalDeptSalary​(PropEmp)

Here:

  • Dept is the grouping attribute.
  • SUM(Salary) adds the salaries in each department.
  • TotalDeptSalary is the name of the calculated result.

The output contains one summary row per department.

The grouping attribute may be omitted when the goal is to calculate one summary value for the entire relation rather than one value for each group.

For example, a count over an entire relation could be represented conceptually as:

γCOUNT(ID)→TotalRecords(R)\gamma_{\text{COUNT}(ID)\rightarrow\text{TotalRecords}}(R)γCOUNT(ID)→TotalRecords​(R)

Aggregation is useful when the query asks for totals, averages, counts, smallest values, or largest values rather than individual rows.


6.3 Outer Join

A regular join returns only tuples that satisfy the join condition. An outer join also preserves tuples that do not have a matching tuple in the other relation.

For an unmatched tuple, the missing attributes from the other relation are filled with NULL.

There are three forms:

  1. Left outer join
  2. Right outer join
  3. Full outer join

Left outer join

A left outer join keeps every tuple from the left relation. Matching tuples from the right relation are included, and unmatched right-side attributes receive NULL.

Conceptually:

R \leftouterjoin SR \ \leftouterjoin\ SR \leftouterjoin S

If relation AAA contains numbers and their squares, while relation BBB contains numbers and their cubes, and number 444 appears only in AAA, then the result still includes number 444, but its cube value is NULL.

In a database example, a left outer join between Employees and Photographers keeps all employees, even employees who are not photographers. The photographer attributes are NULL for employees without a matching photographer record.

Right outer join

A right outer join keeps every tuple from the right relation. Matching tuples from the left relation are included, and unmatched left-side attributes receive NULL.

If number 555 appears only in relation BBB, a right outer join still includes number 555, but its square value from relation AAA is NULL.

In an employee example, a right outer join can keep every employee while matching them against senior employee records. Senior-related attributes become NULL where no matching senior record satisfies the condition.

Full outer join

A full outer join keeps every tuple from both relations.

  • Matching tuples are combined.
  • Unmatched tuples from the left relation receive NULL values for right-side attributes.
  • Unmatched tuples from the right relation receive NULL values for left-side attributes.

If number 444 appears only in AAA and number 555 appears only in BBB, a full outer join includes both numbers. The missing square or cube values are represented by NULL.

A full outer join between Boat and Car based on equal prices includes all boats and all cars. If a boat has no car with the same price, car-related attributes are NULL. If a car has no boat with the same price, boat-related attributes are NULL.

Why outer joins matter

Outer joins preserve information that an ordinary join would discard. They are especially useful when the query asks for:

  • All employees, including those without related records.
  • All customers, including those without purchases.
  • All products, including products with no matching sales.
  • All records from both tables, even when some do not match.

The bracketed portion of an outer join symbol indicates which relation must be preserved completely.


6.4 Outer Union

An outer union is similar to a union, but it can combine relations that share some attributes without requiring all attributes to be fully compatible.

The common attributes are merged, while attributes that exist in only one relation are included with NULL values where necessary.

Outer union can be understood as being similar to a full outer join based on common attributes.

Suppose relation AAA contains:

  • Var
  • Value
  • Max

and relation BBB contains:

  • Var
  • Value
  • Increment

The common attributes are Var and Value. The Max attribute appears only in AAA, while Increment appears only in BBB.

An outer union produces a relation containing:

  • The common attributes.
  • The Max attribute.
  • The Increment attribute.
  • Tuples from both relations.
  • NULL values where a tuple has no value for an attribute from the other relation.

The result can contain values of different compatible types in corresponding columns. If an attribute has a defined numeric type, a missing value may be represented using a type-appropriate default such as 000 in the example. If no suitable type is specified, a missing value may appear as NULL.

Outer join versus outer union

  • An outer join combines tuples based on a matching condition.
  • An outer union merges the structures and tuples of relations with common attributes.
  • Both can preserve unmatched information using NULL values.

Think About It

A student deciding between ordinary and outer join should ask: “Should unmatched records disappear, or must they remain visible?” If they must remain visible, an outer join is appropriate. If the goal is to merge relations with overlapping but not identical attributes, outer union is more suitable.


7. Combining Operations to Solve Queries

Relational algebra becomes most powerful when operations are combined.

A complex query can often be solved by following this sequence:

  1. Select the rows that meet the condition.
  2. Project the attributes needed in the result.
  3. Rename attributes if compatibility or clarity requires it.
  4. Join related relations.
  5. Apply a set operation if relations must be united, intersected, or compared.
  6. Aggregate if totals or summaries are required.
  7. Use assignment to name intermediate results.

Example: Making relations compatible

Suppose Actors and Directors are not union-compatible. A direct union produces an error because their structures do not match.

A solution is to project matching attributes from Actors, such as:

πID, FirstName, LastName(Actors)\pi_{\text{ID, FirstName, LastName}}(Actors)πID, FirstName, LastName​(Actors)

If necessary, the attributes can also be renamed so that their names correspond to those in Directors. The adjusted relation can then be combined with Directors.

This demonstrates that relational algebra operations can prepare data for later operations.

Example: Filtering and projecting

To find actors whose names start with “Ch”:

σFirstName LIKE Ch% OR LastName LIKE Ch%(Actors)\sigma_{\text{FirstName LIKE Ch\% OR LastName LIKE Ch\%}}(Actors)σFirstName LIKE Ch% OR LastName LIKE Ch%​(Actors)

The exact condition depends on whether the pattern applies to the first name, last name, or both. If only names are required in the output, projection can be applied afterward:

πFirstName, LastName(σname condition(Actors))\pi_{\text{FirstName, LastName}} \left( \sigma_{\text{name condition}}(Actors) \right)πFirstName, LastName​(σname condition​(Actors))

Example: Filtering and renaming

To retrieve actors whose first name is Stanley and rename the output attributes:

ρFName, LName(πFirstName, LastName(σFirstName=Stanley(Actors)))\rho_{\text{FName, LName}} \left( \pi_{\text{FirstName, LastName}} \left( \sigma_{\text{FirstName}=\text{Stanley}}(Actors) \right) \right)ρFName, LName​(πFirstName, LastName​(σFirstName=Stanley​(Actors)))

The expression first identifies the correct rows, then keeps the desired columns, and finally changes their names.

Example: Combining relations and filtering

Assignment can simplify a multi-stage query:

T←Actors×MovieGenresT \leftarrow Actors \times MovieGenresT←Actors×MovieGenres

Then:

σGenre=Action(T)\sigma_{\text{Genre}=\text{Action}}(T)σGenre=Action​(T)

The first expression creates all combinations, and the second keeps only combinations involving the action genre.

In practice, a join condition or additional restrictions are often used to avoid unnecessary combinations.


8. Exercises and Applications

The following exercises apply the operations discussed.

Set-operation exercises

Using appropriate unary operations and set operations, a student can formulate queries for:

  1. The first and last names of writers and administrators.
  2. The clients who are administrators.
  3. Administrators who are not writers.
  4. The Cartesian product of writers, clients, and administrators.

These problems demonstrate that relational algebra expressions can be nested and combined. They also emphasize that unary operations such as selection and projection may be needed before a set operation can be applied.

Unary-operation exercises

Using an actors relation:

  1. Find all actors whose names start with “Ch.”
  2. Find actors whose first name is Stanley.
  3. Return only their first and last names.
  4. Rename those attributes to FName and LName.

The general structure is:

ρFName, LName(πFirstName, LastName(σFirstName=Stanley(Actors)))\rho_{\text{FName, LName}} \left( \pi_{\text{FirstName, LastName}} \left( \sigma_{\text{FirstName}=\text{Stanley}}(Actors) \right) \right)ρFName, LName​(πFirstName, LastName​(σFirstName=Stanley​(Actors)))

Binary-operation exercises

Using PC and laptop relations:

  1. Join laptops and PCs to find PCs that are more expensive than a laptop.
  2. Select and project PCs with a specified hard-drive value.
  3. Divide the laptop relation using the selected PC attribute.

These exercises require the student to combine selection, projection, join, and division rather than using one operation alone.

Extended-operation exercises

Two important applications are:

  1. Use generalized projection to calculate the total cost of each laptop after adding a delivery charge of 200200200:
πModel, Price+200→TotalCost(Laptop)\pi_{\text{Model},\ \text{Price}+200\rightarrow\text{TotalCost}}(Laptop)πModel, Price+200→TotalCost​(Laptop)
  1. Use an outer join with a department relation to retrieve a list of employees, preserving employees even when a corresponding department record is missing.

Integrated challenge

An integrated query can retrieve the number of movies directed by each director when:

  • The movie rank is at least 888.
  • The movie was shown from 196019601960 through 200020002000.
  • The results are grouped by director.
  • The number of movies is counted for each director.

A solution would require a combination of:

  1. Selection for the rank and year conditions.
  2. A join between movies and directors.
  3. Projection of the director information.
  4. Aggregation using COUNT.
  5. Grouping by director.

A conceptual form is:

γDirector; COUNT(Movie)→MovieCount(Director⋈σRank≥8 AND 1960≤Year≤2000(Movie))\gamma_{\text{Director};\ \text{COUNT(Movie)}\rightarrow\text{MovieCount}} \left( \text{Director} \bowtie \sigma_{\text{Rank}\geq 8\ \text{AND}\ 1960\leq\text{Year}\leq 2000} (\text{Movie}) \right)γDirector; COUNT(Movie)→MovieCount​(Director⋈σRank≥8 AND 1960≤Year≤2000​(Movie))

The exact expression depends on the attribute names and relationships in the database schema.


Comprehensive Review

Relational algebra provides a formal method for manipulating relational database tables. Its operations are composable: because every operation returns a relation, the result of one operation can be used as the input to another.

The central ideas are:

  • A relation is a table.
  • A tuple is a row.
  • An attribute is a column.
  • A domain defines the allowed values for an attribute.
  • Union compatibility requires corresponding relation structures and domains to match.

The set operations work as follows:

  • Union returns tuples from either relation and removes duplicates.
  • Intersection returns only tuples common to both relations.
  • Set difference returns tuples in the first relation but not the second, so operand order matters.
  • Cartesian product pairs every tuple from one relation with every tuple from the other.

The unary operations work on one relation:

  • Selection filters rows using a condition.
  • Projection filters columns and removes duplicate results.
  • Rename changes relation or attribute names.
  • Assignment stores an intermediate result in a temporary relation variable.

The binary operations combine two relations:

  • Theta join uses any comparison condition.
  • Equijoin uses equality only.
  • Natural join matches same-named, compatible attributes and removes duplicate join attributes.
  • Division returns tuples associated with every tuple in another relation.

The extended operations add further capabilities:

  • Generalized projection calculates new attributes using arithmetic expressions.
  • Aggregation summarizes values with functions such as SUM, AVERAGE, COUNT, MIN, and MAX.
  • Outer joins preserve unmatched tuples and fill missing attributes with NULL.
  • Outer union combines relations with common attributes even when their structures are not completely identical.

Together, these operations allow relational algebra to express queries ranging from simple row filtering to complex tasks involving joins, derived values, grouping, counting, and preservation of unmatched records.

Ask anything

We've read this whole study set, so questions about it get the best answers.

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent