Database Management SystemUnit 515 min read
Relational Algebra: Fundamental, Additional, and Extended Operations
Unit 5 of Database Management System covers formal procedural query languages, detailing fundamental unary and binary relational algebra operations, derived joins and division, aggregate grouping, and query evaluation techniques for relational schemas.
Key points
- Relational algebra is a procedural query language that operates on relations and produces relations as results, preserving closure.
- The six fundamental operations are Select (\(\sigma\)), Project (\(\pi\)), Rename (\(\rho\)), Union (\(\cup\)), Set Difference (\(-\)), and Cartesian Product (\(\times\)).
- Derived operations like Set Intersection (\(\cap\)), Natural Join (\(\bowtie\)), and Division (\(\div\)) can be expressed using fundamental operations.
- Extended relational operators introduce aggregate functions (\(\Im\)) and grouping to handle practical business reporting needs.
- Relational algebra forms the theoretical foundation for query execution plans and query optimization inside relational database engines.
Introduction to Relational Algebra
Relational Algebra is a formal, procedural query language associated with the Relational Data Model. It takes one or more relations as input and produces a new relation as output.
A query in relational algebra specifies the operational steps needed to compute the desired result. The language adheres to the closure property: since the operands are relations and the output is always a relation, operations can be nested and composed into complex algebraic expressions.
+--------------------+
| Input Relation(s) |
+--------------------+
|
v
+--------------------+
| Relational Algebra | ---> [Evaluates using selection, projection, joins, etc.]
| Operation |
+--------------------+
|
v
+--------------------+
| Output Relation | ---> [Satisfies closure property: can be input to next op]
+--------------------+
Fundamental Operations of Relational Algebra
There are six fundamental operators from which all other algebraic operations can be derived:
- Selection () — Unary
- Projection () — Unary
- Rename () — Unary
- Union () — Binary
- Set Difference () — Binary
- Cartesian Product () — Binary
1. Select Operation ()
The Select operation chooses horizontal subsets of tuples from a relation that satisfy a specified selection condition (predicate).
- Notation:
- Condition Syntax: Boolean expression combining comparison operators () and logical connectors ().
- Degree and Cardinality:
- Degree of = Degree of (attribute count remains unchanged).
- Cardinality .
Example: Given relation Student(SID, SName, Dept, Year):
This extracts all fourth-year CSIT students with all their attributes.
2. Project Operation ()
The Project operation chooses vertical subsets of attributes from a relation, discarding all other columns. Because relations are formal mathematical sets, duplicate tuples are automatically eliminated from the resulting projection.
- Notation:
- Degree and Cardinality:
- Degree = Number of attributes in the attribute list.
- Cardinality (strictly less if duplicates are removed).
Example: To get only student names and departments:
3. Rename Operation ()
The Rename operation provides an identifier to intermediate relations resulting from sub-expressions and allows renaming of attributes.
- Notation:
- : Renames relation to .
- : Renames relation to and its attributes to .
- : Renames only the attributes of relation .
4. Union Operation ()
The Union of two relations and produces a relation containing all tuples that appear in , in , or in both. Duplicates are eliminated.
- Precondition (Union Compatibility / Type Compatibility):
- and must have the exact same degree (number of attributes).
- The domain of the -th attribute of must match the domain of the -th attribute of for all .
- Notation:
5. Set Difference Operation ()
The Set Difference of and returns tuples that are present in relation but absent in relation .
- Precondition: and must be union-compatible.
- Notation:
- Note: (non-commutative).
6. Cartesian Product (Cross Product) ()
The Cartesian Product combines every tuple of relation with every tuple of relation .
- Notation:
- Characteristics:
- If has degree and cardinality , and has degree and cardinality :
- Degree of .
- Cardinality of .
Additional (Derived) Relational Operations
These operations simplify queries and can be rewritten using the fundamental operations.
1. Set Intersection ()
Finds tuples that belong to both relations and .
- Precondition: and must be union-compatible.
- Derivation:
2. Theta Join ()
Theta join applies a selection condition on the Cartesian product of two relations: The condition is of the form , where .
3. Equijoin
A Theta join where the comparison operator across all joining attributes is strictly equality (). The resulting relation contains duplicate attribute columns holding identical values from both relations.
4. Natural Join ( or )
Natural Join is an equijoin performed over all common attributes of relations and , where duplicate join columns are projected out automatically.
- Derivation: Let and , where are the common attributes.
Trace Example: Natural Join
Given Relations and :
Table R
| ID | Course |
|---|---|
| 101 | DBMS |
| 102 | OS |
Table S
| ID | Room |
|---|---|
| 101 | C-201 |
| 103 | D-104 |
Result of :
| ID | Course | Room |
|---|---|---|
| 101 | DBMS | C-201 |
Tuple with ID = 102 is dropped because 102 does not exist in . Tuple with ID = 103 is dropped because 103 does not exist in .
5. Outer Joins
Outer joins preserve tuples that do not satisfy the join condition by filling missing attribute values with NULL.
- Left Outer Join (): Retains all tuples from the left relation . Tuples without a match in have
NULLvalues for all attributes of . - Right Outer Join (): Retains all tuples from the right relation . Missing attributes from are populated with
NULL. - Full Outer Join (): Retains all tuples from both and , padding mismatches with
NULL.
Left Outer Join (R =< S):
+--------------------+--------------------+
| Matches from R & S | Dangling from R | (S columns = NULL)
+--------------------+--------------------+
Right Outer Join (R >= S):
+--------------------+--------------------+
| Matches from R & S | Dangling from S | (R columns = NULL)
+--------------------+--------------------+
Full Outer Join (R =<= S):
+--------------------+--------------------+--------------------+
| Matches from R & S | Dangling from R | Dangling from S |
+--------------------+--------------------+--------------------+
6. Division Operation ()
The division operator applies when answering queries containing phrases like "for all" or "for every".
- Let and . The relation is the set of all tuples such that for every tuple , the tuple exists in .
- Derivation using fundamental operations:
Trace Example: Division
Table Takes(StudentID, CourseID)
| StudentID | CourseID |
|---|---|
| S1 | C1 |
| S1 | C2 |
| S2 | C1 |
| S3 | C1 |
| S3 | C2 |
| S3 | C3 |
Table Compulsory(CourseID)
| CourseID |
|---|
| C1 |
| C2 |
Evaluating :
- All distinct students: .
- All combinations of students with compulsory courses:
- Courses not taken:
- Students missing at least one compulsory course:
- Difference gives qualified students:
Extended Relational Operations
Standard relational algebra cannot compute aggregate properties (averages, counts, maximums) or retain duplicates when necessary. Extended operations address these limitations.
1. Generalized Projection
Allows arithmetic functions and expressions in the projection list:
Example: On relation Employee(ID, Salary, Bonus):
2. Aggregate Functions and Grouping
Aggregates apply functions over collections of values from a column (e.g., COUNT, SUM, AVG, MIN, MAX).
- Notation:
- If no grouping attribute is specified, the aggregate evaluates across the entire relation.
Example: Find total salary and number of instructors per department:
Relational Operations Comparison
| Feature | Cartesian Product () | Natural Join () | Equijoin () |
|---|---|---|---|
| Join Condition | None | Implicit equality on identically named attributes | Explicit equality condition |
| Output Degree | |||
| Duplicate Attributes | Both sets kept | Duplicate common columns eliminated | Both sets kept |
| Predicate Type | Cross combinations |
Comprehensive Worked Exam Problems
Problem 1: School and Teacher Database
Given Relational Schema:
TEACHER(TID, TName, TAddress, TQualification)SCHOOL(SID, SName, SAddress, SPhone)SCHOOL_TEACHER(SID, TID, No_of_Period)
Query: Retrieve the TName and No_of_Period of teachers who teach in "ABC" school.
Step-by-Step Algebraic Formulation:
- Filter the school record for "ABC":
- Join with the association relation
SCHOOL_TEACHER: - Join the result with
TEACHERto obtain instructor details: - Project the required columns:
Single Line Expression:
Problem 2: University Student Database
Given Relational Schema:
Student(SID, SName, Dept, Year)Course(CID, CName, Credit)Enroll(SID, CID, Grade)
Query A: Find names of all students enrolled in the course named "DBMS".
- Select course tuple where
CName = 'DBMS': - Join with
Enroll: - Join with
Student: - Project
SName:
Query B: Find SID of students who have enrolled in both 'C101' and 'C102'.
Using set intersection:
Query C: Find the names of students who have NOT enrolled in any course.
- All students:
- Students who have enrolled in at least one course:
- Set difference:
- Retrieve names:
Query D: Find students who have enrolled in ALL courses offered.
This represents a standard universal quantification problem solved by Division ():
Problem 3: Banking Database
Given Relational Schema:
Customer(CustomerID, CustomerName, Address, Phone, Email)Borrows(CustomerID, LoanNumber)Loan(LoanNumber, LoanType, Amount)
Query: Find the names of customers who have a loan with an amount greater than 500,000.
Applications and Importance in Query Optimization
Relational algebra is not merely an academic notation; it serves direct practical purposes in database engine architecture:
- Internal Representation: Relational database management systems translate SQL queries into equivalent relational algebra expressions, represented internally as query trees.
- Equivalence Rules and Optimization: The database query optimizer applies algebraic transformation rules to swap operations. For instance: Pushing selections down past joins drastically cuts the size of intermediate relations, saving memory and CPU cycles during joins.
- Execution Plans: Leaf nodes of an operator tree correspond to base relations stored on disk, internal nodes correspond to relational operators, and the root produces the query answer.
Query Optimization via Selection Push-down
Unoptimized Plan Optimized Plan
pi(TName) pi(TName)
| |
sigma(Dept='CSIT') join
| / \
join sigma(Dept='CSIT') Enroll
/ \ |
Student Enroll Student
Exam Tips
- Check Union Compatibility First: When writing , , or , verify that both operands project the identical number of attributes with compatible types. Writing will receive zero marks; project common attributes first, such as .
- Projection List Reductions: Never project attributes before applying selection conditions on those attributes unless you include the predicate attribute in the projection. Always apply selections as early as possible.
- Handling "ALL" Questions: Whenever an exam question uses phrases like "teachers who teach all subjects", "customers who have accounts in all branches", or "students enrolled in every course", identify it immediately as a Division operation ().
- Join Subscripts: When using Theta Join, specify the join condition explicitly in the subscript (e.g., ). If using Natural Join (), ensure the schema has identical attribute names for the join key.
- Show Intermediate Relations: Break down complex relational algebra answers using assignment arrows () and numbered steps (). This clarifies your logic and secures partial credit even if a final projection has a syntax oversight.
Based on the TU BSc CSIT syllabus for Database Management System (CSC265), unit 5.
Discussion
Loading…