DBMS Hub

Relational Algebra (Lecture 15)

Introduction to Relational Algebra

1. Introduction to Relational Algebra

Relational Algebra is a foundational mathematical framework for the relational database model. It provides a basic set of operations that allow a user to specify data retrieval requests (queries).

Key Concept: The result of every relational algebra operation is a new relation (a new table).

  • You can take the result of one operation and use it as input for the next operation.
  • A sequence of these operations forms a Relational Algebra Expression.

Why is Relational Algebra Important?

  1. Foundation of the Relational Model: It defines the rules for manipulating data.
  2. Query Optimization: Relational Database Management Systems (RDBMS) use Relational Algebra internally to determine the fastest way to execute a SQL query.
  3. SQL Standard: Some of its concepts are built directly into the SQL language we use today.

Groups of Relational Operations

The operations are divided into four main groups:

  • Unary Operations: Work on a single relation.
  • Set Theory Operations: Standard math set operations applied to relations.
  • Binary Relational Operations: Work on two relations to combine them.
  • Additional Operations: Extensions for advanced needs (aggregates, outer joins, recursion).

2. The COMPANY Database Schema (Example Data)

To understand every example in this lecture, we will use the COMPANY database. Below is the Entity-Relationship schema of the database followed by the sample data provided in the slides.

Schema Diagram (Referential Integrity):

Sample Data Tables

EMPLOYEE Table:

FnameMinitLnameSsnBdateAddressSexSalarySuper_ssnDno
JohnBSmith1234567891965-01-09731 Fondren, Houston, TXM300003334455555
FranklinTWong3334455551955-12-08638 Voss, Houston, TXM400008886655555
AliciaJZelaya9998877771968-01-193321 Castle, Spring, TXF250009876543214
JenniferSWallace9876543211941-06-20291 Berry, Bellaire, TXF430008886655554
RameshKNarayan6668844441962-09-15975 Fire Oak, Humble, TXM380003334455555
JoyceAEnglish4534534531972-07-315631 Rice, Houston, TXF250003334455555
AhmadVJabbar9879879871969-03-29980 Dallas, Houston, TXM250009876543214
JamesEBorg8886655551937-11-10450 Stone, Houston, TXM55000NULL1

DEPARTMENT Table:

DnameDnumberMgr_ssnMgr_start_date
Research53334455551988-05-22
Administration49876543211995-01-01
Headquarters18886655551981-06-19

DEPT_LOCATIONS Table:

DnumberDlocation
1Houston
4Stafford
5Bellaire
5Sugarland
5Houston

WORKS_ON Table:

EssnPnoHours
123456789132.5
12345678927.5
666884444340.0
453453453120.0
453453453220.0
333445555210.0
333445555310.0
3334455551010.0
3334455552010.0
9998877773030.0
9998877771010.0
9879879871035.0
987987987305.0
9876543213020.0
9876543212015.0
88866555520NULL

PROJECT Table:

PnamePnumberPlocationDnum
ProductX1Bellaire5
ProductY2Sugarland5
ProductZ3Houston5
Computerization10Stafford4
Reorganization20Houston1
Newbenefits30Stafford4

DEPENDENT Table:

EssnDependent_nameSexBdateRelationship
333445555AliceF1986-04-05Daughter
333445555TheodoreM1983-10-25Son
333445555JoyF1958-05-03Spouse
987654321AbnerM1942-02-28Spouse
123456789MichaelM1988-01-04Son
123456789AliceF1988-12-30Daughter
123456789ElizabethF1967-05-05Spouse

3. Unary Relational Operations

Unary operations work on one single table (relation).

3.1 The SELECT Operation (σ\sigma)

  • Symbol: σ\sigma (Sigma).
  • Purpose: It acts as a horizontal filter. It selects a subset of rows (tuples) from a relation based on a specific condition. Rows that meet the condition are kept; rows that fail are discarded.
  • General Formula: σ⟨selection condition⟩(R)\sigma_{\langle\text{selection condition}\rangle}(R)

Examples:

  1. Select employees who work in Department 4:

σDNO=4(EMPLOYEE)\sigma_{DNO=4}(EMPLOYEE)

  1. Select employees whose salary is greater than $30,000:

σSALARY>30000(EMPLOYEE)\sigma_{SALARY \gt 30000}(EMPLOYEE)

  1. Select employees in Department 4 AND having a salary > 25,000:

σDNO=4  ∧  SALARY>25000(EMPLOYEE)\sigma_{DNO=4 \;\wedge\; SALARY \gt 25000}(EMPLOYEE)

SQL Equivalent: In SQL, the SELECT operation is written in the WHERE clause.

SELECT * FROM EMPLOYEE WHERE Dno = 4 AND Salary > 25000;

Properties of SELECT:

  1. Commutative: You can perform SELECTs in any order.

σc1(σc2(R))=σc2(σc1(R))\sigma_{c1}(\sigma_{c2}(R)) = \sigma_{c2}(\sigma_{c1}(R))

  1. Cascade Combination: A sequence of SELECTs is equivalent to a single SELECT with an AND condition.

σc1(σc2(R))=σc1  ∧  c2(R)\sigma_{c1}(\sigma_{c2}(R)) = \sigma_{c1 \;\wedge\; c2}(R)

  1. Row Count: The number of rows in the result will always be less than or equal to the number of rows in the original relation RR.

3.2 The PROJECT Operation (π\pi)

  • Symbol: π\pi (Pi).
  • Purpose: It acts as a vertical filter. It selects a subset of columns (attributes) from a relation and discards the rest.
  • General Formula: π⟨attribute list⟩(R)\pi_{\langle\text{attribute list}\rangle}(R)

Example: To list only the last name, first name, and salary of all employees:

πLNAME,  FNAME,  SALARY(EMPLOYEE)\pi_{LNAME,\; FNAME,\; SALARY}(EMPLOYEE)

Important Rule: The PROJECT operation automatically removes duplicate rows. Because the result of a projection must be a mathematical set, and sets do not allow duplicate elements.

SQL Equivalent: In SQL, the PROJECT operation is written in the SELECT clause.

SELECT DISTINCT Gender, Salary FROM EMPLOYEE;

Properties of PROJECT:

  1. Not Commutative: You cannot swap the order of the attribute lists. πL1(πL2(R))=πL1(R)\pi_{L1}(\pi_{L2}(R)) = \pi_{L1}(R) only if L2L2 contains all attributes in L1L1.

  2. Tuple Count: The number of rows in the result is less than or equal to the number of rows in RR because duplicates are removed.

Example of Combined SELECT and PROJECT

Request: Find the first name, last name, and salary of employees who work in department 5.

Relational Expression:

πFNAME,  LNAME,  SALARY(σDNO=5(EMPLOYEE))\pi_{FNAME,\; LNAME,\; SALARY}(\sigma_{DNO=5}(EMPLOYEE))

(Note: The SELECT runs first, creating an intermediate table of department 5 employees. Then PROJECT keeps only the 3 requested columns.)

Result:

FnameLnameSalary
JohnSmith30000
FranklinWong40000
RameshNarayan38000
JoyceEnglish25000

3.3 The RENAME Operation (ρ\rho)

  • Symbol: ρ\rho (Rho).
  • Purpose: To give a new name to a relation, its columns, or both. This is incredibly useful for self-joins.
  • General Formula (3 forms):
    1. ρS(B1,  B2,  …,  Bn)(R)\rho_{S(B1,\; B2,\; \ldots,\; Bn)}(R) — Renames relation RR to SS and renames the columns.
    2. ρS(R)\rho_{S}(R) — Renames the relation name only.
    3. ρ(B1,  B2,  …,  Bn)(R)\rho_{(B1,\; B2,\; \ldots,\; Bn)}(R) — Renames the column names only.

SQL Equivalent:

SELECT E.Fname AS First_name, E.Lname AS Last_name
FROM EMPLOYEE E
WHERE E.Dno = 5;

4. Relational Algebra Operations from Set Theory

These are standard mathematical set operations, but they require Union Compatibility.

Union Compatibility Rule: Two relations RR and SS are compatible if:

  1. They have the exact same number of attributes (columns).
  2. The domain (data type) of each column in RR matches the corresponding column in SS.

4.1 UNION (∪\cup)

  • Result: All tuples that are in RR, in SS, or in both. Duplicates are automatically removed.
  • Example — Find the SSN of employees who work in Dept 5 OR supervise an employee in Dept 5:

DEP5_EMPS←σDNO=5(EMPLOYEE)DEP5\_EMPS \leftarrow \sigma_{DNO=5}(EMPLOYEE)

RESULT1←πSSN(DEP5_EMPS)RESULT1 \leftarrow \pi_{SSN}(DEP5\_EMPS)

RESULT2(SSN)←πSUPERSSN(DEP5_EMPS)RESULT2(SSN) \leftarrow \pi_{SUPERSSN}(DEP5\_EMPS)

RESULT←RESULT1∪RESULT2RESULT \leftarrow RESULT1 \cup RESULT2

Diagram of Result:

RESULT1 (SSN)RESULT2 (SSN)RESULT (SSN)
123456789333445555123456789
333445555888665555333445555
666884444666884444
453453453453453453
888665555

4.2 INTERSECTION (∩\cap)

  • Result: Only tuples that are in both RR and SS.
  • Example:

RESULT←RESULT1∩RESULT2RESULT \leftarrow RESULT1 \cap RESULT2

This gives SSNs of people who both work in department 5 AND supervise someone in department 5.

4.3 SET DIFFERENCE (−-)

  • Result: Tuples that are in RR but NOT in SS.
  • Important: Set difference is NOT commutative. R−S≠S−RR - S \neq S - R.

Visual Example of UNION, INTERSECTION, SET DIFFERENCE

(a) STUDENT(a) INSTRUCTOR(b) UNION(c) INTERSECTION(d) STUDENT − INSTRUCTOR(e) INSTRUCTOR − STUDENT
Susan, YaoJohn, SmithSusan, YaoSusan, YaoJohnny, KohlerJohn, Smith
Ramesh, ShahRicardo, BrowneRamesh, ShahRamesh, ShahBarbara, JonesRicardo, Browne
Johnny, KohlerSusan, YaoJohnny, KohlerAmy, FordFrancis, Johnson
Barbara, JonesFrancis, JohnsonBarbara, JonesJimmy, Wang
Amy, FordRamesh, ShahAmy, FordErnest, Gilbert
Jimmy, WangJimmy, Wang
Ernest, GilbertErnest, Gilbert
John, Smith
Ricardo, Browne
Francis, Johnson

4.4 CARTESIAN PRODUCT (×\times)

  • Symbol: ×\times (Cross Product).
  • Purpose: Combines every tuple from RR with every tuple from SS.
  • Mathematical Properties:
    • If RR has nn columns and SS has mm columns, the result has n+mn + m columns.
    • If RR has nRnR rows and SS has nSnS rows, the result has nR×nSnR \times nS rows.
  • RR and SS do NOT need to be union-compatible.
  • By itself rarely meaningful — but becomes powerful when followed by SELECT. In fact: Join = Cartesian Product + Select.

Example:

FEMALE_EMPS←σSex=′F′(EMPLOYEE)FEMALE\_EMPS \leftarrow \sigma_{Sex='F'}(EMPLOYEE)

EMPNAMES←πFNAME,  LNAME,  SSN(FEMALE_EMPS)EMPNAMES \leftarrow \pi_{FNAME,\; LNAME,\; SSN}(FEMALE\_EMPS)

EMP_DEPENDENTS←EMPNAMES×DEPENDENTEMP\_DEPENDENTS \leftarrow EMPNAMES \times DEPENDENT

ACTUAL_DEPS←σSSN=ESSN(EMP_DEPENDENTS)ACTUAL\_DEPS \leftarrow \sigma_{SSN = ESSN}(EMP\_DEPENDENTS)


5. Binary Relational Operations: JOIN

Because Cartesian Product + SELECT is such a common pattern, Relational Algebra provides a dedicated shortcut: The JOIN operation (⋈\bowtie).

5.1 The JOIN Operation (⋈\bowtie)

  • General Formula: R⋈join conditionSR \bowtie_{\text{join condition}} S
  • Purpose: Combine related tuples from two tables, discarding unrelated ones.
  • Example (Theta-Join): Find the manager details for each department.

DEPT_MGR←DEPARTMENT⋈MGRSSN=SSNEMPLOYEEDEPT\_MGR \leftarrow DEPARTMENT \bowtie_{MGRSSN = SSN} EMPLOYEE

5.2 The EQUIJOIN

  • The most common type of Join — uses only the equality (=) operator.
  • Side Effect: The result includes the two matching columns twice (once from each table), holding identical values.

5.3 The NATURAL JOIN (∗*)

  • Symbol: ∗*
  • Purpose: A cleaner EQUIJOIN that is automatic.
  • Automatic Matching: Automatically joins on attributes with the exact same name in both relations.
  • Removes Duplicates: Automatically removes the redundant duplicate column.

Example 1:

DEPT_LOCS←DEPARTMENT∗DEPT_LOCATIONSDEPT\_LOCS \leftarrow DEPARTMENT * DEPT\_LOCATIONS

(Both have column DNUMBER, so it joins on DEPARTMENT.DNUMBER = DEPT_LOCATIONS.DNUMBER and shows DNUMBER only once.)

Example 2:

PROJ_DEPT←PROJECT∗DEPARTMENTPROJ\_DEPT \leftarrow PROJECT * DEPARTMENT

Result of PROJ_DEPT:

PnamePnumberPlocationDnumDnameMgr_ssnMgr_start_date
ProductX1Bellaire5Research3334455551988-05-22
ProductY2Sugarland5Research3334455551988-05-22
Computerization10Stafford4Administration9876543211995-01-01

6. The Complete Set of Relational Algebra Operations

The Relational Algebra is mathematically complete. Any complex operation can be expressed using only these 6 fundamental operations:

  1. SELECT (σ\sigma)
  2. PROJECT (π\pi)
  3. UNION (∪\cup)
  4. SET DIFFERENCE (−-)
  5. RENAME (ρ\rho)
  6. CARTESIAN PRODUCT (×\times)

Proof of Completeness:

R∩S  =  (R∪S)−((R−S)∪(S−R))R \cap S \;=\; (R \cup S) - ((R - S) \cup (S - R))

R⋈conditionS  =  σcondition(R×S)R \bowtie_{\text{condition}} S \;=\; \sigma_{\text{condition}}(R \times S)


7. The DIVISION Operation

  • Symbol: ÷\div
  • Purpose: Used to answer queries like "Find the employee who works on ALL projects."
  • How it works: Given R(Z)÷S(X)R(Z) \div S(X) where X⊆ZX \subseteq Z, the result is a relation T(Y)T(Y) where Y=Z−XY = Z - X.
  • The Logic: A tuple tt appears in the result only if tt appears in RR in combination with every single tuple in SS. This is the equivalent of a "FOR ALL" (Universal Quantifier).

8. Additional Relational Operations

8.1 Aggregate Functions and Grouping (F\mathcal{F})

Basic Relational Algebra cannot calculate summary statistics. The Aggregate Function operation F\mathcal{F} solves this.

Common Aggregates: SUM, AVERAGE, MAXIMUM, MINIMUM, COUNT.

Formula with grouping:

Grouping  Attribute  FFunction1,  Function2(Relation){}_{Grouping\;Attribute}\; \mathcal{F}_{Function1,\; Function2}(Relation)

Example 1 — Max salary from EMPLOYEE:

FMAX  Salary(EMPLOYEE)\mathcal{F}_{MAX\;Salary}(EMPLOYEE)

Example 2 — Per department: count employees and average salary:

DNO  FCOUNT  SSN,  AVERAGE  Salary(EMPLOYEE){}_{DNO}\; \mathcal{F}_{COUNT\;SSN,\; AVERAGE\;Salary}(EMPLOYEE)

Result:

DnoCount_ssnAverage_Salary
5433250
4331000
1155000

8.2 OUTER JOIN Operations

In a standard Join, rows with no match are dropped. Outer Joins keep them, filling missing values with NULL.

  1. LEFT OUTER JOIN: Keeps every tuple in RR. Missing SS attributes become NULL.
  2. RIGHT OUTER JOIN: Keeps every tuple in SS. Missing RR attributes become NULL.
  3. FULL OUTER JOIN: Keeps every tuple in both RR and SS.

Example of LEFT OUTER JOIN:

FnameMinitLnameDname
JohnBSmithNULL
FranklinTWongResearch
AliciaJZelayaNULL
JenniferSWallaceAdministration
RameshKNarayanNULL
JamesEBorgHeadquarters

(John Smith has NULL for Dname — he has no department, but the Left Outer Join keeps him in the result.)

8.3 OUTER UNION

Normal UNION requires perfectly type-compatible tables. OUTER UNION works on partially compatible relations:

  • Common columns appear once.
  • Unique columns from both relations are included.
  • Missing values are padded with NULL.

Example: STUDENT(Name, SSN, Department, Advisor) OUTER UNION INSTRUCTOR(Name, SSN, Department, Rank) produces: STUDENT_OR_INSTRUCTOR(Name, SSN, Department, Advisor, Rank)

8.4 RECURSIVE CLOSURE

Recursive operations cannot be expressed in basic Relational Algebra. They handle self-referential relationships like the Employee-Supervisor relationship.

Goal: Find all employees supervised by James Borg at all levels.

Step 1 — Find Borg's SSN:

BORG_SSN←πSsn(σFname=′James′  ∧  Lname=′Borg′(EMPLOYEE))BORG\_SSN \leftarrow \pi_{Ssn}(\sigma_{Fname='James' \;\wedge\; Lname='Borg'}(EMPLOYEE))

Step 2 — Build a SUPERVISION table:

SUPERVISION(Ssn1,Ssn2)←πSsn,  Super_ssn(EMPLOYEE)SUPERVISION(Ssn1, Ssn2) \leftarrow \pi_{Ssn,\; Super\_ssn}(EMPLOYEE)

Step 3 — Level 1 (direct reports):

RESULT1(Ssn)←πSsn1(SUPERVISION⋈Ssn2=SsnBORG_SSN)RESULT1(Ssn) \leftarrow \pi_{Ssn1}(SUPERVISION \bowtie_{Ssn2 = Ssn} BORG\_SSN)

Step 4 — Level 2 (reports of direct reports):

RESULT2(Ssn)←πSsn1(SUPERVISION⋈Ssn2=SsnRESULT1)RESULT2(Ssn) \leftarrow \pi_{Ssn1}(SUPERVISION \bowtie_{Ssn2 = Ssn} RESULT1)

Step 5 — All levels combined:

RESULT←RESULT1∪RESULT2RESULT \leftarrow RESULT1 \cup RESULT2

(In a real RDBMS this is done with WITH RECURSIVE SQL, but in basic Relational Algebra you manually repeat the join for each level.)


9. Query Trees

A Query Tree (Query Evaluation Tree / Execution Tree) is an internal data structure used by a DBMS to represent a query.

  • Leaf Nodes: Represent input relations (tables).
  • Internal Nodes: Represent relational algebra operations (σ\sigma, π\pi, ⋈\bowtie, etc.).

Execution Order:

  1. Leaf nodes (raw tables) are loaded.
  2. Internal node operations execute when their child operands are ready.
  3. The result of each internal node replaces that node.
  4. Execution ends when the root node produces the final result.

Standard logical order (Bottom to Top):

  1. SELECT (σ\sigma) — Filter rows early to reduce data size.
  2. JOIN (⋈\bowtie) — Combine the filtered tables.
  3. PROJECT (π\pi) — At the root, output only the requested columns.

10. Practice Examples

Q1 — Retrieve the name and address of all employees who work for the 'Research' department:

RESEARCH_DEPT←σDNAME=′Research′(DEPARTMENT)RESEARCH\_DEPT \leftarrow \sigma_{DNAME='Research'}(DEPARTMENT)

RESEARCH_EMPS←RESEARCH_DEPT⋈DNUMBER=DNOEMPLOYEERESEARCH\_EMPS \leftarrow RESEARCH\_DEPT \bowtie_{DNUMBER = DNO} EMPLOYEE

RESULT←πFNAME,  LNAME,  ADDRESS(RESEARCH_EMPS)RESULT \leftarrow \pi_{FNAME,\; LNAME,\; ADDRESS}(RESEARCH\_EMPS)

Q2 — Find names of employees who work on ALL projects controlled by department 5:

PROJ_DEPT5(PNO)←πPnumber(σDnum=5(PROJECT))PROJ\_DEPT5(PNO) \leftarrow \pi_{Pnumber}(\sigma_{Dnum=5}(PROJECT))

EMP_PROJ(SSN,PNO)←πEssn,  Pno(WORKS_ON)EMP\_PROJ(SSN, PNO) \leftarrow \pi_{Essn,\; Pno}(WORKS\_ON)

RESULT_SSN←EMP_PROJ÷PROJ_DEPT5RESULT\_SSN \leftarrow EMP\_PROJ \div PROJ\_DEPT5

RESULT←πLNAME,  FNAME(RESULT_SSN∗EMPLOYEE)RESULT \leftarrow \pi_{LNAME,\; FNAME}(RESULT\_SSN * EMPLOYEE)

Q3 — List project numbers involving an employee with last name 'Smith' (as worker OR department manager):

SMITH_EMPS(SSN)←πSSN(σLNAME=′Smith′(EMPLOYEE))SMITH\_EMPS(SSN) \leftarrow \pi_{SSN}(\sigma_{LNAME='Smith'}(EMPLOYEE))

PROJ_WORKER(PNO)←πPno(SMITH_EMPS∗WORKS_ON)PROJ\_WORKER(PNO) \leftarrow \pi_{Pno}(SMITH\_EMPS * WORKS\_ON)

PROJ_MGR(PNO)←πPnumber(SMITH_EMPS∗DEPARTMENT⋈DNUMBER=DnumPROJECT)PROJ\_MGR(PNO) \leftarrow \pi_{Pnumber}(SMITH\_EMPS * DEPARTMENT \bowtie_{DNUMBER = Dnum} PROJECT)

RESULT←PROJ_WORKER∪PROJ_MGRRESULT \leftarrow PROJ\_WORKER \cup PROJ\_MGR

Q6 — Retrieve names of employees who have NO dependents:

ALL_EMPS←πSSN(EMPLOYEE)ALL\_EMPS \leftarrow \pi_{SSN}(EMPLOYEE)

EMPS_WITH_DEPS(SSN)←πESSN(DEPENDENT)EMPS\_WITH\_DEPS(SSN) \leftarrow \pi_{ESSN}(DEPENDENT)

EMPS_WITHOUT_DEPS←ALL_EMPS−EMPS_WITH_DEPSEMPS\_WITHOUT\_DEPS \leftarrow ALL\_EMPS - EMPS\_WITH\_DEPS

RESULT←πLNAME,  FNAME(EMPS_WITHOUT_DEPS∗EMPLOYEE)RESULT \leftarrow \pi_{LNAME,\; FNAME}(EMPS\_WITHOUT\_DEPS * EMPLOYEE)


11. Summary of Chapter 6

  • Relational Algebra is a mathematical language for manipulating relations.
  • Unary Operations: SELECT (σ\sigma — filter rows), PROJECT (π\pi — filter columns), RENAME (ρ\rho — rename relation/columns).
  • Set Theory Operations: UNION (∪\cup), INTERSECTION (∩\cap), SET DIFFERENCE (−-), CARTESIAN PRODUCT (×\times). All require Union Compatibility except Cartesian Product.
  • Binary Relational Operations: JOIN (⋈\bowtie), EQUIJOIN, NATURAL JOIN (∗*) — combine related data from multiple tables.
  • Other Operations: DIVISION (÷\div), AGGREGATE FUNCTIONS (F\mathcal{F}) with GROUPING, OUTER JOINS, OUTER UNION, RECURSIVE CLOSURE.
  • Completeness: The 6 fundamental operations (SELECT, PROJECT, UNION, SET DIFFERENCE, RENAME, CARTESIAN PRODUCT) can express all other operations.
  • Query Trees are internal diagrams the DBMS optimizer uses to plan the fastest execution path for a query.

On this page