Relational Algebra
Relational Algebra
1. Foundations of Relational Algebra
Relational algebra is a data-manipulation language for the relational model of databases. It is a procedural language, meaning that a user specifies both:
The data that should be retrieved.
The operations and sequence of operations used to retrieve it.
Relational algebra is based on operations that take one or two relations as input and produce a new relation as output. Because the result of every operation is itself a relation, operations can be combined into larger expressions.
Relational algebra is closed under its operations: relations are used as inputs, and new relations are produced as results.
A relational algebra query can therefore be written as a sequence of operations that progressively filters, combines, transforms, or summarizes data.
Components of a Relational Algebra Expression
Relational algebra expressions contain two primary components:
Operands: Relations or variables representing relations.
Operators: Operations that map one or more relations to another relation.
The rules governing how operands and operators are combined determine the meaning and evaluation of a relational algebra expression.
For example, if R and S are relations:
uses R and S as operands and ∪ as the operator.
2. Relations, Tuples, Attributes, and Domains
Several terms are essential when working with relational algebra.
Set
A set is a collection of objects of the same general type. In relational algebra, the objects in a set are usually tuples.
Tuple
A tuple is an immutable, ordered sequence of values. In a relational database, a tuple corresponds to a row or record.
For example, a tuple in an actors relation might contain:
Relation
A relation is a set of tuples. In a database, a relation corresponds to a table.
A relation contains:
A relation name.
A set of attributes.
A set of tuples.
A domain associated with each attribute.
Attribute
An attribute is a field or column in a relation. Examples include:
idfirst_namelast_namesalary
Degree
The degree of a relation is the number of attributes or columns it contains.
For example:
A relation with four attributes has degree 4.
A relation with eight attributes has degree 8.
Domain
A domain is the set of permitted values for an attribute. It also establishes the attribute’s data type.
For example:
A salary attribute may use a numeric domain.
A name attribute may use a character-string domain.
A birth date attribute may use a date domain.
Union Compatibility
Two relations are union-compatible when:
They have the same degree.
Corresponding attributes have compatible domains.
Union compatibility is required for union, intersection, and set-difference operations.
For example, if relation R has four attributes and relation S also has four attributes, they may be union-compatible if the first attribute in each relation has compatible domains, the second attributes have compatible domains, and so on.
3. Types of Relational Algebra Operations
Relational algebra operations are grouped into four categories:
Set operations: Union, intersection, set difference, and Cartesian product.
Unary operations: Operations involving one input relation, including selection, projection, rename, and assignment.
Binary operations: Operations involving two input relations, including theta join, equijoin, natural join, and division.
Extended operations: Generalized projection, aggregation, outer join, and outer union.
Set Operations
Set operations are mathematical operations applied to relations. Except for Cartesian product, the major set operations require the input relations to be union-compatible.
Set operations are binary operations because they use two input relations.
4. Union
The union of two relations contains every tuple that appears in either relation.
It is written as:
Properties
Both relations must be union-compatible.
The result has the same degree as the input relations.
Duplicate tuples are eliminated.
A tuple appearing in both relations appears only once in the result.
Formally:
If relation writers and relation clients each contain four compatible attributes, their union contains all tuples from both relations, with duplicates removed.
Example
Suppose:
writerscontains John Cena, Mary, and Harold.clientscontains John Cena, Joy, and another tuple.
Then:
contains every distinct tuple from both relations. John Cena appears once even though it occurs in both relations.
5. Intersection
The intersection of two relations contains only tuples that appear in both relations.
It is written as:
Properties
Both relations must be union-compatible.
The result has the same degree as the input relations.
Duplicate tuples are eliminated.
Only common tuples are retained.
Formally:
Example
If John Cena is the only tuple found in both writers and clients, then:
returns only John Cena.
Intersection is useful when the goal is to identify records shared by two groups.
6. Set Difference
The set difference of relation R and relation S contains tuples that belong to R but do not belong to S.
It is written as:
Properties
Both relations must be union-compatible.
The result has the same degree as the input relations.
The order of the operands affects the result.
Duplicate tuples are eliminated.
Formally:
Operand Order
The expressions R−S and S−R generally produce different results.
For example:
returns writers who are not clients.
Conversely:
returns clients who are not writers.
If John Cena appears in both relations, it is excluded from both difference results because it is not unique to either relation.
7. Cartesian Product
The Cartesian product combines every tuple in one relation with every tuple in another relation.
It is written as:
Each tuple from R is concatenated with every tuple from S.
Degree of the Result
The degree of the result is the sum of the degrees of the two input relations:
If both R and S contain four attributes, the resulting relation contains eight attributes.
Cardinality of the Result
If R contains m tuples and S contains n tuples, then the Cartesian product contains:
tuples.
Important Properties
The relations do not need to be union-compatible.
Every tuple of R is paired with every tuple of S.
The attributes of both relations appear in the result.
Cartesian products are often used as an intermediate step in join operations.
Example
For relations writers and clients, the product:
pairs every writer tuple with every client tuple. If writers has three tuples and clients has four tuples, the result contains:
tuples.
8. Combining Operations
Relational algebra operations can be nested and combined. Unary operations are often applied first to make relations compatible or reduce the amount of data before applying a set operation.
For example, if actors and directors are not union-compatible, a projection can select matching attributes from actors:
This projected relation may then be unioned with directors, provided the attributes and domains now match.
General Strategy
A useful approach for complex queries is:
Apply selection to filter unnecessary rows.
Apply projection to retain only required columns.
Rename attributes or relations when necessary.
Apply the required set or join operation.
Apply another projection or selection to produce the final form.
Unary Operations
9. Unary Operations
A unary operation takes one relation as input and produces one relation as output.
The four unary operations are:
Selection
Projection
Rename
Assignment
10. Selection
The selection operation returns the tuples that satisfy a specified condition.
Selection is a horizontal filter because it filters rows while retaining the relation’s attributes.
It is represented by the Greek letter sigma:
General Form
where:
σ is the selection operator.
conditionspecifies which tuples are retained.R is the input relation.
Conditions
Selection conditions may use:
Equality: =
Inequality: =
Less than: <
Greater than: >
Less than or equal to: ≤
Greater than or equal to: ≥
Logical
ANDLogical
ORPattern matching such as
LIKE
Example: Last Name Filter
To select actors whose last name ends with a particular pattern:
Only tuples satisfying the last-name condition are returned.
Example: Multiple Conditions
To retrieve movies released in 2003 with a rank greater than 7:
The result contains only movies satisfying both conditions.
Key Feature
Selection reduces the number of tuples but does not normally reduce the number of attributes.
11. Projection
The projection operation returns selected attributes from a relation.
Projection is a vertical filter because it filters columns while retaining qualifying tuples.
It is represented by the Greek letter pi:
General Form
where A1,A2,…,An are the attributes to retain.
Example: First Names Only
To retrieve only first names from actors:
Example: First and Last Names
To retrieve first and last names of actors whose first name is Michael:
The selection is performed first, and the projection then keeps only the required attributes.
Key Feature
Projection reduces the number of attributes. Duplicate tuples produced by removing columns are eliminated because relations are sets.
12. Selection Versus Projection
Selection
Filters rows.
Uses a condition.
Represented by σ.
Retains the original attributes.
Example: all movies with rank greater than 7.
Projection
Filters columns.
Uses an attribute list.
Represented by π.
Retains only the specified attributes.
Example: first and last names of actors.
A query often combines both operations: selection identifies the required rows, and projection identifies the required columns.
13. Rename
The rename operation changes the name of a relation, its attributes, or both.
Rename is useful when:
Two relations have confusing or conflicting names.
A relation must be referenced multiple times.
Attribute names need to be made compatible.
A query requires disambiguation after a join.
The rename operator is commonly represented by rho:
Renaming a Relation
To rename directors as producers:
The tuples and attributes remain the same, but the relation name changes.
Renaming Attributes
A relation’s attributes can also be renamed:
For example, the attributes id, first_name, and last_name could be renamed as:
director_idf_namel_name
Renaming Both Relation and Attributes
A relation and its attributes can be renamed together:
Renaming changes the labels, not the underlying tuple values.
14. Assignment
The assignment operation stores the result of a relational algebra expression in a temporary relation variable.
It is useful for expressing complex queries as a sequence of manageable steps.
The general form is:
where:
T is a temporary relation variable.
E is a relational algebra expression.
Example
First, select male actors:
The temporary relation male_actors can then be used in another expression.
Sequential Query Example
A complex query can be written as:
Then:
The assignment makes the intermediate product available for subsequent filtering.
Benefits
Breaks complex queries into sequential steps.
Makes intermediate results easier to inspect.
Allows temporary relations to be reused.
Functions similarly to variables in a programming language.
Binary Operations
15. Binary Operations
A binary operation combines two input relations into one output relation.
The binary operations covered are:
Theta join
Equijoin
Natural join
Division
Joins commonly use selection and projection as part of the query process.
16. Theta Join
A theta join combines tuples from two relations when they satisfy a specified comparison condition.
It is also called a conditional join.
The general form is:
where θ is a comparison condition.
Valid Comparison Operators
A theta join may use:
=
=
<
>
≤
≥
Example
To join pc and laptop where the PC has more RAM than the laptop:
Only pairs satisfying the RAM comparison are included.
Interpretation
For each tuple in the first relation:
Compare it with tuples in the second relation.
Test the specified condition.
Include the pair if the condition is true.
A theta join is more selective than a Cartesian product because it retains only matching pairs.
17. Equijoin
An equijoin is a theta join that uses only equality as its comparison condition.
The general form is:
Example
To join pc and laptop where the RAM values are equal:
Only PC and laptop tuples with the same RAM value are returned.
Difference from Theta Join
A theta join can use any comparison operator.
An equijoin uses only equality.
Both relations’ join attributes generally remain in the result, which can lead to duplicate-looking columns.
18. Natural Join
A natural join joins two relations automatically using attributes that have:
The same name.
Compatible domains.
At least one common attribute between the relations.
It is represented by:
How Natural Join Works
A natural join:
Identifies common attributes.
Matches tuples where those attributes have equal values.
Combines the matching tuples.
Eliminates duplicate copies of the common attributes.
Example
If product and pc both contain an attribute named model, then:
matches tuples with the same model value and includes the common model attribute only once.
Practical Example
To identify laptop models and their makers:
Project
makerandmodelfromproduct.Naturally join the result with
laptop.
The result identifies which product maker produces each laptop model.
Natural Join Versus Equijoin
Natural Join
Automatically uses same-named attributes.
Requires at least one common attribute.
Removes duplicate copies of common attributes.
Equijoin
Explicitly specifies the equality condition.
The compared attributes may have different names.
Usually retains both join attributes.
19. Division
The division operation returns tuples from one relation that are associated with every tuple in another relation.
It is useful for queries containing phrases such as:
“Related to all.”
“Works on every project.”
“Compatible with every required item.”
“Has all specified properties.”
The general form is:
Conceptual Meaning
Suppose relation R contains attributes (X,Y) and relation S contains attribute Y. Then:
returns the X values that are paired with every Y value in S.
Example
If laptop is divided by selected PC speed values, the result contains laptop models associated with every speed in the divisor relation.
The attributes used for division do not appear in the result. If the divisor uses speed, the result may contain only attributes such as:
modelprice
Example with RAM
To find laptops associated with every PC having a RAM value of 1024:
Select PCs whose RAM is 1024.
Project the RAM attribute.
Divide the laptop relation by the projected relation.
Conceptually:
Then:
The result contains laptop tuples satisfying the universal requirement.
Extended Operations
20. Extended Relational Algebra
Extended operations increase the expressive power of basic relational algebra.
The operations covered are:
Generalized projection
Aggregation
Outer join
Outer union
21. Generalized Projection
Generalized projection extends ordinary projection by allowing arithmetic expressions and computed attributes in the projection list.
The general form is:
where:
E is a relation algebra expression.
F1,F2,…,Fn are attributes or arithmetic expressions.
Computed expressions can be assigned new attribute names.
Example: Credit Consumed
Suppose credit_info contains:
customer_namecredit_limitcredit_balance
The amount of credit currently consumed can be calculated as:
The generalized projection is:
The result contains:
The customer name.
A computed
credit_consumedvalue.
Other Possible Expressions
Generalized projection can perform calculations such as:
Adding delivery charges.
Subtracting discounts.
Multiplying quantity by unit price.
Calculating balances.
Renaming calculated results.
For example, the total cost of a laptop after a delivery charge of 200 is:
22. Aggregation
Aggregation applies a function to a collection of values and returns a summarized result.
Common aggregate functions include:
SUMAVERAGECOUNTMINMAX
Aggregation is represented by the grouping and aggregation operator, commonly written as γ.
General Form
The grouping attributes may be omitted when one summary value is required for the entire relation.
Example: Total Salary by Department
If propEmp contains employee departments and salaries, the total salary per department can be calculated as:
The result contains one tuple for each department and its total salary.
Grouping
When a grouping attribute is present:
Tuples are divided into groups based on the grouping attribute.
The aggregate function is applied independently to each group.
One result tuple is produced per group.
For example, grouping by dept produces a separate salary total for each department.
Without Grouping
If the grouping attribute is omitted, the aggregate function is applied to the entire relation:
This produces a single overall average.
23. Outer Join
An outer join extends an ordinary join by retaining tuples that do not have matching tuples in the other relation.
For unmatched attributes, the result contains NULL values.
Outer joins are especially useful when the query must preserve all records from one or both relations, even when matching data is absent.
There are three forms:
Left outer join
Right outer join
Full outer join
24. Left Outer Join
A left outer join retains every tuple from the left relation.
Matching tuples from the right relation are combined.
If a left tuple has no match, the right-side attributes are padded with
NULL.
Conceptually:
Example
Suppose:
employeescontains all employees.photographerscontains only employees who are photographers.
A left outer join of employees with photographers retains all employees. Employees who are not photographers have NULL values in the photographer attributes.
The result therefore has the same complete set of employee tuples as the left relation.
25. Right Outer Join
A right outer join retains every tuple from the right relation.
Matching tuples from the left relation are combined.
If a right tuple has no match, the left-side attributes are padded with
NULL.
Conceptually:
Example
If seniors is the left relation and employees is the right relation, a right outer join retains all employees. Employees without a matching senior record receive NULL values for the senior attributes.
26. Full Outer Join
A full outer join retains all tuples from both relations.
Matching tuples are combined.
Unmatched tuples from the left receive
NULLvalues for right-side attributes.Unmatched tuples from the right receive
NULLvalues for left-side attributes.
Conceptually:
Example
Suppose:
Relation
Acontains numbers and their squares.Relation
Bcontains numbers and their cubes.
If number 4 appears only in A, the cube attribute from B is NULL.
If number 5 appears only in B, the square attribute from A is NULL.
The full outer join preserves both unmatched tuples.
27. Outer Join Comparison
Left Outer Join
Keeps all tuples from the left relation.
Adds
NULLvalues to missing right-side attributes.
Right Outer Join
Keeps all tuples from the right relation.
Adds
NULLvalues to missing left-side attributes.
Full Outer Join
Keeps all tuples from both relations.
Adds
NULLvalues wherever a matching tuple is absent.
The bracket or directional portion of the outer-join notation indicates which relation must be preserved completely.
28. Outer Union
An outer union combines tuples from two relations while allowing the relations to have attributes that are not fully compatible.
It is similar to ordinary union but can handle:
Common attributes.
Attributes present in only one relation.
Common attributes whose data types may not be fully compatible.
Conceptually, outer union resembles a full outer join based on common attributes, with the common attributes merged.
Example
Suppose relation A contains:
varvaluemax
Relation B contains:
varvalueincrement
The common attributes are:
varvalue
The outer union merges the common columns and preserves the non-common columns:
maxincrement
Tuples that lack a value for a non-common attribute receive NULL or an appropriate default value, depending on the system and data type.
Important Characteristics
Common attributes are combined.
Attributes found only in one relation are still retained.
Missing values are filled with
NULLor a type-compatible default.The operation is useful when two relations represent related information but do not have identical schemas.
RelaX Calculator Application
RelaX is an online relational algebra calculator that can be used to construct and execute relational algebra expressions.
A typical workflow is:
Load a dataset.
View the available relations.
Enter a relational algebra expression.
Execute the query.
Inspect the resulting relation.
A relation can often be loaded by typing its name or selecting the relation from the available dataset.
The calculator is useful for testing:
Syntax.
Intermediate results.
Set operations.
Unary operations.
Joins.
Aggregations.
Extended operations.
Practice Applications
29. Set Operation Query Tasks
The following types of queries demonstrate how operations can be combined.
First and Last Names of Writers and Administrators
A projection can first select the required attributes, followed by a union:
This requires the projected relations to be union-compatible.
Clients Who Are Administrators
If clients and admins have compatible schemas:
If only certain attributes are required, projection can be applied before or after the intersection.
Administrators Who Are Not Writers
The administrator relation is the base relation, so the result contains administrators absent from the writers relation.
Product of Writers, Clients, and Administrators
A Cartesian product involving three relations can be written as:
Parentheses clarify the order of evaluation.
30. Binary Operation Practice Tasks
PCs More Expensive Than Laptops
A theta join can compare PC and laptop prices:
Projection can then retain only the desired attributes.
PCs with a Specified Hard-Drive Value
A selection filters PCs by hard-drive capacity:
A projection can then retain the required attributes:
Division Query
A relation containing required PC values can be created through selection and projection, then used as a divisor:
This returns laptops associated with every selected RAM value.
31. Unary Operation Practice Tasks
Actors Whose Names Start with “Ch”
A selection using a pattern condition can be used:
The exact pattern syntax depends on the relational algebra calculator.
Actors Named Stanley
First select tuples with the specified first name:
Then project the required attributes:
Finally, rename the attributes:
32. Extended Operation Practice Tasks
Laptop Cost Including Delivery
Generalized projection can calculate the total cost:
The expression keeps the laptop model and computes a new total cost that includes a 200 delivery charge.
Employees Using an Outer Join
An outer join with the department relation can preserve employees even when an employee does not have a matching department record.
A left outer join is appropriate when all employees must appear in the result:
The exact join condition depends on the common employee or department identifier.
Final Challenge
A comprehensive query can combine selection, grouping, and aggregation.
The challenge is to determine the number of movies directed by each director when the movies satisfy all of the following conditions:
The movie rank is at least 8.
The movie was shown from 1960 through 2000.
Results are grouped by director.
The number of qualifying movies is counted for each director.
A conceptual sequence is:
Select movies whose rank satisfies:
Select movies whose year satisfies:
Join the qualifying movies with the director information.
Group the result by director.
Count the movies in each group.
A conceptual relational algebra expression is:
The central principle is that relational algebra queries can be built by combining simple operations into increasingly complex expressions that retrieve, transform, join, and summarize relational data.

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