10 - Relational Algebra

1624 words
8 min read
Python Week 1: the first filter for runtime behavior
Visual companion
Python
Type and operator map

Python Week 1: the first filter for runtime behavior

View
Revision summary

What this note is really saying

Short form

# 10 - Relational Algebra ## ๐ŸŽฏ Learning Objectives After reading this topic, you will be able to: - Write relational algebra expressions for database queries - Use ฯƒ (select), ฯ€ (project), ฯ (rename), โˆช (union), โˆ’ (difference), โˆฉ (intersection), ร— (Cartesian product) - Write join expressions (natural join, theta jo...

10 - Relational Algebra

๐ŸŽฏ Learning Objectives

After reading this topic, you will be able to:
  • Write relational algebra expressions for database queries
  • Use ฯƒ (select), ฯ€ (project), ฯ (rename), โˆช (union), โˆ’ (difference), โˆฉ (intersection), ร— (Cartesian product)
  • Write join expressions (natural join, theta join, outer join)
  • Use the division operator (รท) for "all" queries
  • Translate between relational algebra and SQL

๐Ÿ“‹ Prerequisites

  • 03 - Relational Model โ€” Relations, tuples, attributes, keys
  • Set theory from BSMA1001 (Maths 1) โ€” Sets, subsets, set operations

๐Ÿ“– Core Content

10.1 Intuition: The Mathematical Foundation of SQL

Relational algebra is the theoretical foundation of SQL. Every SQL query can be translated to a relational algebra expression. While SQL is declarative (WHAT), relational algebra is procedural (HOW). Think of it as a recipe:
  1. Take the instructor relation
  2. Select rows where salary > 80000
  3. Project only name and dept_name In relational algebra: ฯ€name,deptname(ฯƒsalary>80000(instructor))\pi_{name, dept_name}(\sigma_{salary > 80000}(instructor))
Why This Matters: Understanding relational algebra helps you:
  • Write complex SQL queries correctly
  • Understand what the query optimizer does
  • Reason about query equivalence and optimization

10.2 The Basic Operations

Select: ฯƒ\sigma (Sigma)

Selects rows based on a condition:
ฯƒcondition(relation)\sigma_{condition}(relation) ฯƒdeptname=โ€ฒComp.Sci.โ€ฒ(instructor)\sigma_{dept_name = 'Comp. Sci.'}(instructor)
Returns all instructors in Comp. Sci.
ฯƒsalary>80000โˆงdeptname=โ€ฒFinanceโ€ฒ(instructor)\sigma_{salary > 80000 \land dept_name = 'Finance'}(instructor)
Returns Finance instructors earning > 80000.
SymbolMeaning
ฯƒc(R)\sigma_{c}(R)Select rows from R satisfying condition c
โˆง\landAND
โˆจ\lorOR
ยฌ\lnotNOT

Project: ฯ€\pi (Pi)

Selects columns (attributes):
ฯ€name,salary(instructor)\pi_{name, salary}(instructor)
Returns only the name and salary columns.
ฯ€deptname(instructor)\pi_{dept_name}(instructor)
Returns department names (WITHOUT duplicates โ€” unlike SQL's default behavior).

Rename: ฯ\rho (Rho)

Renames relations and/or attributes:
ฯX(A1,A2,โ€ฆ,An)(E)\rho_{X(A_1, A_2, \dots, A_n)}(E)
Returns the result of expression E with the name X and attributes renamed to A1,A2,โ€ฆ,AnA_1, A_2, \dots, A_n.
ฯemp(ID,n,d,s)(instructor)\rho_{emp(ID, n, d, s)}(instructor)
Renames instructor to emp and its columns to ID, n, d, s.

10.3 Set Operations

All set operations require union compatibility: same number of columns, same data types.

Union: โˆช\cup

rโˆชs={tโˆฃtโˆˆrย orย tโˆˆs}r \cup s = \{t \mid t \in r \text{ or } t \in s\} ฯ€courseid(teachesFall)โˆชฯ€courseid(teachesSpring)\pi_{course_id}(teaches_Fall) \cup \pi_{course_id}(teaches_Spring)
Courses taught in Fall OR Spring.

Difference: โˆ’- (or โˆ–\setminus)

rโˆ’s={tโˆฃtโˆˆrย andย tโˆ‰s}r - s = \{t \mid t \in r \text{ and } t \notin s\} ฯ€courseid(teachesFall)โˆ’ฯ€courseid(teachesSpring)\pi_{course_id}(teaches_Fall) - \pi_{course_id}(teaches_Spring)
Courses taught in Fall but NOT in Spring.

Intersection: โˆฉ\cap

rโˆฉs={tโˆฃtโˆˆrย andย tโˆˆs}r \cap s = \{t \mid t \in r \text{ and } t \in s\}
Can be expressed using difference: rโˆฉs=rโˆ’(rโˆ’s)r \cap s = r - (r - s)
ฯ€courseid(teachesFall)โˆฉฯ€courseid(teachesSpring)\pi_{course_id}(teaches_Fall) \cap \pi_{course_id}(teaches_Spring)
Courses taught in BOTH Fall and Spring.

10.4 Cartesian Product: ร—\times

Every combination of tuples from both relations:
rร—s={tqโˆฃtโˆˆrย andย qโˆˆs}r \times s = \{t q \mid t \in r \text{ and } q \in s\}
If instructor has 12 tuples and teaches has 15 tuples:
ฯƒinstructor.ID=teaches.ID(instructorร—teaches)\sigma_{instructor.ID = teaches.ID}(instructor \times teaches)
This is equivalent to a JOIN. In practice, Cartesian product is almost always followed by a select condition.

10.5 Join Operations

Theta Join: โ‹ˆฮธ\bowtie_\theta

Rโ‹ˆฮธS=ฯƒฮธ(Rร—S)R \bowtie_\theta S = \sigma_\theta(R \times S) instructorโ‹ˆinstructor.ID=teaches.IDteachesinstructor \bowtie_{instructor.ID = teaches.ID} teaches

Natural Join: โ‹ˆ\bowtie

Joins on all common attributes (removes duplicate columns):
Rโ‹ˆSR \bowtie S instructorโ‹ˆteachesinstructor \bowtie teaches
Joins on ID (the common attribute). Equivalent to:
ฯ€ID,name,deptname,salary,courseid,...(ฯƒinstructor.ID=teaches.ID(instructorร—teaches))\pi_{ID, name, dept_name, salary, course_id, ...}(\sigma_{instructor.ID = teaches.ID}(instructor \times teaches))

Outer Join

Preserves non-matching rows (like SQL's LEFT/RIGHT/FULL OUTER JOIN):
  • RโŸ•SR โŸ• S โ€” Left outer join
  • RโŸ–SR โŸ– S โ€” Right outer join
  • RโŸ—SR โŸ— S โ€” Full outer join

10.6 Division: รท\div

The division operator answers "all" queries: "Find students who have taken ALL CS courses."
RรทSR \div S
Where attributes(R) โЇ attributes(S). Result has attributes(R) - attributes(S). Intuition: For a tuple t to appear in the result, t must appear in R combined with every tuple in S. (Diagram) Example:
student_idcourse_id
1CS101
1CS201
2CS101
2CS201
3CS101
SS = {CS101, CS201} RรทSR \div S = {1, 2} โ€” students 1 and 2 took BOTH CS101 and CS201. Student 3 only took CS101.

10.7 Equivalence Rules

Important equivalences that the optimizer uses:
  1. Cascade selection: ฯƒฮธ1โˆงฮธ2(E)=ฯƒฮธ1(ฯƒฮธ2(E))\sigma_{\theta_1 \land \theta_2}(E) = \sigma_{\theta_1}(\sigma_{\theta_2}(E))
  2. Commuting selection: ฯƒฮธ1(ฯƒฮธ2(E))=ฯƒฮธ2(ฯƒฮธ1(E))\sigma_{\theta_1}(\sigma_{\theta_2}(E)) = \sigma_{\theta_2}(\sigma_{\theta_1}(E))
  3. Cascade projection: ฯ€L1(ฯ€L2(E))=ฯ€L1(E)\pi_{L_1}(\pi_{L_2}(E)) = \pi_{L_1}(E)
  4. Selection before join: ฯƒฮธ(E1ร—E2)=E1โ‹ˆฮธE2\sigma_\theta(E_1 \times E_2) = E_1 \bowtie_\theta E_2
  5. Commuting join: E1โ‹ˆฮธE2=E2โ‹ˆฮธE1E_1 \bowtie_\theta E_2 = E_2 \bowtie_\theta E_1
  6. Associating join: (E1โ‹ˆE2)โ‹ˆE3=E1โ‹ˆ(E2โ‹ˆE3)(E_1 \bowtie E_2) \bowtie E_3 = E_1 \bowtie (E_2 \bowtie E_3)

10.8 Worked Examples

Example 1: Simple query

Find the names of all instructors in the Physics department.
ฯ€name(ฯƒdeptname=โ€ฒPhysicsโ€ฒ(instructor))\pi_{name}(\sigma_{dept_name = 'Physics'}(instructor))

Example 2: Join query

Find the names of all instructors who teach a course.
ฯ€name(instructorโ‹ˆteaches)\pi_{name}(instructor \bowtie teaches)

Example 3: Division

Find the IDs of students who have taken ALL courses offered in Fall 2017. Let R=ฯ€ID,courseid(takes)R = \pi_{ID, course_id}(takes) Let S=ฯ€courseid(ฯƒsemester=โ€ฒFallโ€ฒโˆงyear=2017(teaches))S = \pi_{course_id}(\sigma_{semester='Fall' \land year=2017}(teaches)) Answer: RรทSR \div S

10.9 Relational Algebra Summary Table

OperationSymbolSQL EquivalentPurpose
Selectฯƒ\sigmaWHEREFilter rows
Projectฯ€\piSELECTChoose columns
Renameฯ\rhoASRename relation/attributes
Unionโˆช\cupUNIONRows in either
Differenceโˆ’-EXCEPTRows in first but not second
Intersectionโˆฉ\capINTERSECTRows in both
Cartesian Productร—\timesCROSS JOINAll combinations
Natural Joinโ‹ˆ\bowtieNATURAL JOINJoin on common attributes
Theta Joinโ‹ˆฮธ\bowtie_\thetaJOIN ON conditionJoin on arbitrary condition
Divisionรท\divNOT EXISTS + EXCEPT"All" queries

โš ๏ธ Common Pitfalls

Pitfall 1: Confusing ฯƒ (select) with SQL SELECT

The Mistake: Thinking ฯƒ is the same as SQL's SELECT. Why It's Wrong: ฯƒ selects rows (filtering), while SQL's SELECT picks columns. The relational algebra equivalent of SQL's SELECT is ฯ€ (project).
ConceptRelational AlgebraSQL
Row filteringฯƒ\sigmaWHERE
Column pickingฯ€\piSELECT
Renamingฯ\rhoAS

Pitfall 2: Forgetting Set Operations Need Union Compatibility

The Mistake: Applying โˆช, โˆฉ, or - to relations with different schemas. Why It's Wrong: Set operations require the same number of attributes with compatible domains. R(A, B) โˆช S(C, D, E) is invalid. Fix: Use project to match schemas: ฯ€A,B(R)โˆชฯ€C,D(S)\pi_{A,B}(R) \cup \pi_{C,D}(S)

Pitfall 3: Thinking Natural Join is Always Equijoin

The Mistake: Assuming natural join always joins on foreign key = primary key. Why It's Wrong: Natural join joins on ALL common attributes. If two tables accidentally share a column name (e.g., both have name), the join uses that too. Fix: Use theta join (โ‹ˆฮธ\bowtie_\theta) to be explicit about join conditions.

๐Ÿ“ Practice Questions

Q1. Write a relational algebra expression to find the names of all instructors who earn more than 90000.

Answer
ฯ€name(ฯƒsalary>90000(instructor))\pi_{name}(\sigma_{salary > 90000}(instructor))
Step 1: ฯƒsalary>90000(instructor)\sigma_{salary > 90000}(instructor) โ€” filter rows with salary > 90000 Step 2: ฯ€name\pi_{name} โ€” keep only the name column

Q2. Express the following SQL query in relational algebra: SELECT name FROM instructor WHERE dept_name = 'Music';

Answer
ฯ€name(ฯƒdeptname=โ€ฒMusicโ€ฒ(instructor))\pi_{name}(\sigma_{dept_name = 'Music'}(instructor))

Q3. Write a relational algebra expression to find course IDs taught in Fall 2017 but not in Spring 2018.

Answer
ฯ€courseid(ฯƒsemester=โ€ฒFallโ€ฒโˆงyear=2017(teaches))โˆ’ฯ€courseid(ฯƒsemester=โ€ฒSpringโ€ฒโˆงyear=2018(teaches))\pi_{course_id}(\sigma_{semester='Fall' \land year=2017}(teaches)) - \pi_{course_id}(\sigma_{semester='Spring' \land year=2018}(teaches))

Q4. What is the division operator? Give an intuitive explanation.

Answer
The division operator (RรทSR \div S) answers "for ALL" queries. For a tuple t to be in the result, t (combined with other attributes) must have a match with every tuple in S.
Example: "Find students who have taken ALL courses offered by the CS department." Use division:
  • R = (student_id, course_id) โ€” all enrollment records
  • S = (course_id) โ€” all CS courses
  • R รท S = students who took every CS course

Q5. Show that intersection can be expressed using difference. RโˆฉS=?R \cap S = ?

Answer
RโˆฉS=Rโˆ’(Rโˆ’S)R \cap S = R - (R - S)
Proof:
  1. Rโˆ’SR - S = tuples in R but not S
  2. Rโˆ’(Rโˆ’S)R - (R - S) = tuples in R minus those not in S = tuples in both R and S = RโˆฉSR \cap S

Q6. Write a relational algebra expression to find the names of instructors and the course IDs they teach.

Answer
ฯ€name,courseid(instructorโ‹ˆteaches)\pi_{name, course_id}(instructor \bowtie teaches)
This natural joins instructor and teaches on ID, then projects name and course_id.

Q7. What is the difference between natural join (โ‹ˆ\bowtie) and theta join (โ‹ˆฮธ\bowtie_\theta)?

Answer
  • Natural join (โ‹ˆ\bowtie): Automatically joins on ALL common attribute names. Duplicate columns are removed from the result.
  • Theta join (โ‹ˆฮธ\bowtie_\theta): Joins based on an explicit condition ฮธ\theta. Can use any comparison operator (=, <, >, etc.). May have duplicate columns.
Natural join is a special case of theta join where ฮธ\theta is equality on all common attributes.

Q8. Translate: ฯ€name(ฯƒdeptname=โ€ฒCSโ€ฒ(instructorโ‹ˆฯƒyear=2018(teaches)))\pi_{name}(\sigma_{dept_name='CS'}(instructor \bowtie \sigma_{year=2018}(teaches))) to English.

Answer
"Find the names of all instructors in the Comp. Sci. department who taught a course in the year 2018."
Step by step:
  1. ฯƒyear=2018(teaches)\sigma_{year=2018}(teaches) โ€” find teaching assignments from 2018
  2. instructorโ‹ˆinstructor \bowtie (step 1) โ€” join with instructor to get instructor details
  3. ฯƒdeptname=โ€ฒCSโ€ฒ\sigma_{dept_name='CS'} โ€” keep only Comp. Sci. instructors
  4. ฯ€name\pi_{name} โ€” return their names

๐Ÿ”— Cross-References

Document outline

Keep your place and jump directly to a heading.

Table of contents

No note selected

Open a chapter to see its outline, backlinks, and sources here.