Relational Algebra: The 6 Fundamental Operations
Overview: To find the names of students who borrowed books, join borrower identifiers with student identifiers first.
What is Relational Algebra?
- Relational Algebra is a formal Procedural Query Language.
- Procedural means it tells the computer HOW to fetch data step-by-step by specifying an exact sequence of mathematical operations.
- While software developers write high-level SQL queries (declarative: “give me this data”), the internal DBMS Query Optimizer immediately…
The Six Fundamental Relational Algebra Operations
- Every query in relational algebra can be constructed using just six fundamental algebraic operators:
- 1. Selection (σ) Filters horizontal rows (tuples) satisfying a given condition.
- 2. Projection (π) Filters vertical columns (attributes) and removes duplicates.
- 3. Cartesian Product (×) Combines every row of table A with every row of table B.
- 4. Union (∪) Combines all rows from two union-compatible tables.
- 5. Set Difference (−) Finds rows present in table A but NOT present in table B.
- 6. Rename (ρ) Renames the relation or its attribute names.
View diagram · The 6 Fundamental Relational Algebra Operators
Selection Operator (σ - Greek letter Sigma)
- Purpose: Selects a subset of tuples (rows) that satisfy a specified predicate (condition).
- Notation:
σ<condition>(Relation_Name) - Comparison Operators allowed:
=,!=,<,<=,>,>= - Logical Operators allowed:
AND (∧),OR (∨),NOT (¬) - Practical Example: Table:
STUDENT(Roll_No, Name, Branch, Marks, City) - Query 1: “Find all students from Indore.”
- Query 2: “Find students in BCA branch with marks greater than 80.”
Projection Operator (π - Greek letter Pi)
- Purpose: Selects specific columns (attributes) from a relation, discarding all other columns.
- Important Note: Relational algebra is based on mathematical set theory.
- Notation:
π<attribute_list>(Relation_Name) - Practical Example: Query 1: “Display the names and marks of all students.”
- Query 2: “List all distinct cities where students live.”
Combining Selection and Projection (Composition)
- In real database queries, Selection and Projection are chained together:
- Selection filters the rows first.
- Projection filters the desired columns from that result.
- Practical Example: Query: “Find the names of all students whose marks are greater than 75.”
Cartesian Product (Cross Product - ×)
- Purpose: Combines every single row of relation
Rwith every single row of relationS. - Properties:
- If
RhasN1tuples and degreeD1, andShasN2tuples and degreeD2: - Resulting Degree =
D1 + D2 - Resulting Cardinality =
N1 × N2 - Notation:
R × S - Practical Example: If
CUSTOMERhas 4 rows andORDERShas 10 rows: CUSTOMER × ORDERSproduces a giant table of4 × 10 = 40 rows.
Set Operations: Union (∪) and Set Difference (−)
- Concept of Union Compatibility: Two relations
RandScan only participate in Union, Intersection, or Set Difference if they are Union-Compatible: - Both relations must have the exact same degree (same number of columns).
- The domains of corresponding columns must be type-compatible (e.g., Column 1 in both must be an integer, Column 2 must be a string).
- A. Union (R ∪ S): Returns all tuples present in
R, orS, or in both (duplicates removed). - Example: Find all persons who are either a Student or an Employee:
- B. Set Difference (R − S): Returns tuples that are in
Rbut NOT in S. - Example: Find all students who have NOT paid their fees:
Rename Operator (ρ - Greek letter Rho)
- Purpose: Renames a relation or changes the names of its attributes.
- Essential when performing self-joins on the same table.
- Notation:
ρ S (R)renames tableRtoS. - Notation:
ρ S(A1, A2, ...) (R)renames tableRtoSand changes its column names toA1, A2, ....
Relational Algebra: Joins, Division Operator, and Assignment
Overview: Selection keeps rows matching a condition.
Introduction: Derived Relational Operations
- While the six fundamental operators (σ, π, ×, ∪, −, ρ) are theoretically sufficient to express any relational algebra query, writing complex…
Set Intersection (∩)
- Purpose: Finds tuples that are present in both relation
RAND relationS. - Requirement:
RandSmust be Union-Compatible. - Equivalence: Can be derived using Set Difference:
- Example: Find students who are enrolled in BOTH Sports Club AND Music Club:
The Family of Join Operations (⋈ - Bowtie Symbol)
- A Join operation combines related tuples from two different relations into single, unified rows based on a matching condition.
- 1. Theta Join (θ-Join) Cross product followed by a condition using any comparison operator (<, >, =, !=).
- 2. Equi-Join A Theta join where the condition strictly uses the equality operator (=).
- 3. Natural Join (⋈) Equi-join on all common attributes, automatically eliminating duplicate columns!
- A. Theta Join (θ-Join): Notation:
R ⋈<condition> S = σ<condition> (R × S) - Combines Cartesian Product and Selection into a single step.
- Example: Find all employees who earn more than their manager:
- B. Equi-Join: A specific variant of Theta Join where the condition is strictly an Equality comparison (
=).
View diagram · The Join Spectrum
Outer Joins (Handling Missing / Unmatched Data)
- In a standard Natural Join or Inner Join, if a tuple in Table A does not match any tuple in Table B, that row is **completely discarded from the…
- Detailed Behavior: Left Outer Join (R ⟕ S):
- Returns all matching tuples from
RandS. - In addition, returns all tuples from
Rthat have no match inS, fillingSattributes withNULL. - Example: List all students, including those who have not registered for any courses yet.
- Right Outer Join (R ⟖ S):
- Returns all matching tuples.
- In addition, returns all tuples from
Sthat have no match inR, fillingRattributes withNULL.
View diagram · The Three Outer Joins
Division Operator (÷)
- The Division Operator (÷) is used for queries that include the phrase “FOR ALL” or “EVERY”.
- Definition: Let
Rhave attributes(A, B)andShave attribute(B). - Classic Exam Scenario: Suppose:
ENROLLMENTtable stores[ Student_Name, Course_Name ].REQUIRED_COURSEStable stores[ Course_Name ]containing:Database SystemsComputer Networks- Query: “Find the names of students who have enrolled in EVERY required course.”
Assignment Operator (←)
- Allows complex relational queries to be split into manageable, sequential steps using temporary relation variables.
- Example:
- Dramatically enhances readability and matches how real programmers think!
Relational Algebra Query Solving: Step-by-Step Practice Guide
Overview: For “students who passed every required paper”, count how demanding the word every is.
The 4-Step Method for Writing Relational Algebra Queries
- In university examinations (DAVV BCA), students are given a standard relational schema and asked to write 5 to 7 relational algebra queries.
- Identify the Target Columns: Look at what the question asks you to display (e.g., “Find the names and salaries…”).
- Identify the Filtering Conditions: Look for criteria (e.g., “salary > 50000”, “department = IT”).
- Identify the Necessary Tables: If all required columns exist in one table, you do not need a join.
- Assemble the Expression: Write from the inside out:
- Borrowing records Read the borrower identifier
- Join with students Match each identifier to its student record
- Project names Return the requested attribute
View diagram · Finding borrowers by name
The Standard Exam Database Schemas
- We will solve queries on two classic university examination schemas:
- Schema A: University System:
STUDENT (Roll_No, Name, Branch, Marks, City) COURSE (Course_ID, Title, Credits, Dept_ID)ENROLL (Roll_No, Course_ID, Grade)DEPARTMENT (Dept_ID, Dept_Name, Building)- Schema B: Enterprise Employee System:
EMPLOYEE (Emp_ID, Emp_Name, Salary, Dept_No, Manager_ID) DEPARTMENT (Dept_No, Dept_Name, Location)PROJECT (Proj_ID, Proj_Name, Budget)
Single Table Query Solutions
- Query 1: “Find the names and branches of all students whose marks are greater than 85.”: Target Columns:
Name, Branch - Condition:
Marks > 85 - Table:
STUDENT - Relational Algebra Expression:
- Query 2: “List all distinct cities where students live.”: Target Columns:
City - Table:
STUDENT - Relational Algebra Expression:
- Query 3: “Find employees who work in Department 10 and earn a salary greater than 45,000.”: Target Columns:
Emp_Name, Salary
Two-Table Join Query Solutions
- Query 4: “Find the names of all students enrolled in the ‘Database Systems’ course.”: Required Tables:
STUDENT,ENROLL,COURSE - Step-by-step using Assignment (←):
- Single-Line Expression:
- Query 5: “Find the names of all employees who work in the ‘Research’ department.”: Required Tables:
EMPLOYEE,DEPARTMENT - Condition:
Dept_Name = 'Research' - Relational Algebra Expression:
- Query 6: “List all employee names along with the projects they are working on.”: Required Tables:
EMPLOYEE,WORKS_ON,PROJECT - Relational Algebra Expression:
Set Operation Query Solutions (Union & Difference)
- Query 7: “Find the roll numbers of students who are enrolled in Course ‘CS101’ OR Course ‘CS102’.”: Solution using Union (∪):
- Query 8: “Find the roll numbers of students who are enrolled in Course ‘CS101’ but NOT in ‘CS102’.”: Solution using Set Difference (−):
- Query 9: “Find the names of students who have enrolled in NO courses whatsoever.”: All students minus students who appear in the
ENROLLtable:
Complex Query: The Division Operator (÷)
- Query 10: “Find the names of students who have enrolled in ALL courses offered by the Computer Science department.”: Step 1: Get all courses offered by Computer Science (
Dept_ID = 'CS'): - Step 2: Get the student-course pairs:
- Step 3: Divide by
CS_Courses: - Step 4: Fetch names:
Tuple Relational Calculus (TRC): Target List and Quantifiers (∃, ∀)
Overview: For “names of students scoring above 70”, a tuple variable ranges over complete student records.
What is Relational Calculus?
- While Relational Algebra is Procedural (“tells the computer HOW to evaluate step-by-step”), Relational Calculus is a…
- In Relational Calculus, you specify WHAT data you want, without describing any sequence of operations to retrieve it.
- Analogy:
- Relational Algebra: “Go to the kitchen, open the fridge, grab 2 eggs, heat the pan, fry them.” (Procedural recipe).
- Relational Calculus: “I want fried eggs on my plate.” (Declarative goal).
- Relational Calculus forms the theoretical mathematical bedrock of SQL (Structured Query Language)!
Structure of a Tuple Relational Calculus (TRC) Query
- A query in TRC is expressed as a set of mathematical tuples:
- Target List (
t): Specifies the resulting tuple format or specific attributes to retrieve (e.g.,t[Name]). - Qualifying Statement / Predicate (
P(t)): A boolean condition that evaluates toTrueorFalsefor each tuplet.
View diagram · General Anatomy of a TRC Expression
Fundamental Components of TRC Formulas
- A predicate formula
P(t)is built from: - Relation Membership:
t ∈ STUDENT(Tupletbelongs to tableSTUDENT). - Attribute Access:
t[Name]ort.Namedenotes the value of attributeNamefor tuplet. - Comparison Conditions:
t[Marks] > 75ort[City] = 'Indore'. - Logical Connectives:
- AND (∧): Both conditions must be True.
- OR (∨): At least one condition must be True.
- NOT (¬): Negates the condition.
The Existential Quantifier (∃ - “There Exists”)
- Symbol: ∃ (Pronounced “There exists at least one”).
- Meaning:
∃ s (P(s))evaluates toTrueif there is at least one tuplesthat makes formulaP(s)true. - Used whenever a query involves checking for a match in another table (similar to a SQL
EXISTSorJOIN). - Practical Example 1: Single Table Query: Query: “Find all student tuples whose marks are greater than 80.”
- Practical Example 2: Projecting Specific Columns: Query: “Find the names and cities of students with marks > 80.”
- Practical Example 3: Two-Table Join: Query: “Find the names of students enrolled in Course ‘CS101’.”
The Universal Quantifier (∀ - “For All”)
- Symbol: ∀ (Pronounced “For all” or “For every”).
- Meaning:
∀ s (P(s))evaluates toTrueif every single tuplesin the universe satisfies conditionP(s). - Used for queries involving phrases like “For all courses”, “Every department”, or “All projects”.
- Relationship Between Quantifiers (De Morgan’s Laws): In mathematical logic and database query engines, any expression written with
∀can be converted into an equivalent expression… ∀ s (P(s)) ≡ ¬ (∃ s (¬ P(s)))∃ s (P(s)) ≡ ¬ (∀ s (¬ P(s)))
Free vs. Bound Variables in Relational Calculus
- Bound Variable: A variable that is quantified using either
∃or∀(e.g.,∃ s (...)meanssis a bound variable). - Free Variable: A variable that is NOT quantified (e.g.,
tin{ t | P(t) }is the free variable that represents the output answer…
Domain Relational Calculus (DRC) and Safety of Expressions
Overview: A domain variable stands for a single value.
What is Domain Relational Calculus (DRC)?
- In Tuple Relational Calculus (TRC), our variables range over entire tuples (rows) of a relation.
Syntax and Structure of a DRC Query
- A query in DRC is written in the following mathematical format:
- `<x1, x2, …
- `P(x1, x2, …
View diagram · Structure of a DRC Expression
Practical DRC Query Examples
- Consider table
STUDENT (Roll_No, Name, Branch, Marks, City). - Query 1: “Find the roll numbers and names of all students from ‘Indore’.”: We create domain variables for each column:
rforRoll_NonforNamebforBranchmforMarkscforCity- DRC Expression:
Comprehensive Comparison: TRC vs. DRC
- Variable Scope: Variables range over entire rows (tuples)
- Basic Syntax: `{ t \
- Attribute Access: Uses dot/bracket notation:
t.Salaryort[Salary] - Practical Influence: Theoretical foundation of SQL
- Quantification: Quantifies entire tuples:
∃ s (...)
Safety of Expressions (Safe vs. Unsafe Queries)
- In theoretical relational calculus, it is possible to write mathematical expressions that produce an INFINITE number of result tuples!
- What does this query mean? It asks for “every tuple in the entire universe that is NOT in the student table”.
- It would return all books, cows, cars, integers, planets, and sentences ever spoken!
- The computer’s memory would instantly crash trying to generate infinite rows.
- The Concept of Domain of a Formula:
dom(P): The Domain of a formulaP(written asdom(P)) is the set of all constant values that appear explicitly in the queryPor in the… - Definition of a Safe Expression:
Expressive Power: Codd’s Equivalence Theorem
- A major milestone in computer science proved by Dr.
- Codd’s Theorem: *The expressive power of Relational Algebra is mathematically EQUIVALENT to the expressive power of Safe Relational…
- Any query that can be written in Relational Algebra can also be written in Safe TRC and Safe DRC, and vice-versa!
- A database query language is declared Relational Complete if it has at least the full expressive power of Relational Algebra.