Database Management SystemUnit 415 min read
Relational Model & Algebra: Tables, Queries & Math
Unit 4 of Database Management System: explores the relational data model (tables, keys, constraints) and relational algebra (operations like select, project, join) with real-world examples from eSewa, Daraz, and NEPSE.
TAKEAWAYS:
- The relational model stores data as tables (relations) with rows (tuples) and columns (attributes), enforcing strict rules like atomicity and uniqueness.
- Relational algebra is a set of 12 operations (e.g.,
SELECT,JOIN) to query and manipulate tables mathematically, not like SQL. - Primary keys uniquely identify tuples, while foreign keys enforce referential integrity between tables (e.g., linking
StudentandEnrollment). - Normalization (covered later) reduces redundancy by applying functional dependencies (e.g.,
Cityshould not repeat for all students). - Cartesian products (cross joins) are the foundation of joins but must be filtered to avoid useless data.
- Relational algebra vs. SQL: Algebra is theoretical (used in optimizers), while SQL is practical (what you write).
1. The Relational Data Model: Tables as the Foundation
The relational model represents data as tables (called relations), where:
- Each table has a name (e.g.,
Student,Course). - Columns are attributes (e.g.,
SID,SName) with a fixed domain (e.g.,VARCHAR(50)). - Rows are tuples (records) with the same structure.
- Keys enforce uniqueness:
- Primary key (PK): Uniquely identifies tuples (e.g.,
SIDinStudent). - Foreign key (FK): References a PK in another table (e.g.,
SIDinEnrollmentlinks toStudent).
- Primary key (PK): Uniquely identifies tuples (e.g.,
Key Properties of Relations
A valid relation must satisfy:
- Atomicity: Each attribute holds a single value (no nested tables or arrays).
- Ordered columns: Columns have a fixed order (though this is often ignored in practice).
- No duplicate tuples: Identical rows are not allowed (unless explicitly modeled).
- No implicit ordering: Rows are unordered unless specified (e.g., by
ORDER BYin SQL).
Example: Student-Course Database
Consider these tables:
erDiagram
STUDENT ||--o{ ENROLLMENT : takes
COURSE ||--o{ ENROLLMENT : enrolls_in
STUDENT {
string SID PK
string SName
string City
string Faculty
}
COURSE {
string CID PK
string CName
int Credits
}
ENROLLMENT {
string SID FK
string CID FK
string Grade
}- Primary keys:
SID(Student),CID(Course). - Foreign keys:
SIDinEnrollment→Student(SID);CIDinEnrollment→Course(CID). - Referential integrity: No
Enrollmentrecord can reference a non-existentStudentorCourse.
| SID | SName | City | Faculty |
|---|---|---|---|
| S001 | Alice | Kathmandu | CS |
| S002 | Bob | Pokhara | Eng |
Why this matters:
- eSewa’s transaction tables use this structure to link users (
User), accounts (Account), and transactions (Transaction). TheTransactiontable has FKs toUserandAccountto track who paid what. - Daraz’s order system stores
Order,Customer, andProductas separate tables with FKs to avoid duplicate customer/product data.
2. Functional Dependencies: The Math Behind Tables
A functional dependency (FD) describes how one attribute determines another. Formally:
X → Y means that if two tuples have the same value for
X, they must also have the same value forY.
Example: Student Table
In Student(SID, SName, City, Faculty):
SID → SName, City, Faculty(a student’s ID uniquely determines their name, city, and faculty).Faculty → City? No, because multiple faculties can share the same city (e.g., Kathmandu has CS, Eng, and Med faculties).
Closure and Determinants
- Closure: Given
X → Y, the closure ofX(denotedX+) includes all attributes functionally dependent onX.- Example: If
SID → SNameandSName → City(unlikely, but possible), thenSID+ = {SName, City}.
- Example: If
- Minimal cover: A set of FDs with no redundant dependencies (used in normalization).
Worked Example: Finding FDs
Given EMPLOYEE(Ssn, Fname, Minit, Lname, Bdate, Address, Sex, Salary, Super_ssn, Dno):
Ssn → Fname, Minit, Lname, Bdate, Address, Sex, Salary, Super_ssn, Dno(PK).Dno → Dname(fromDEPARTMENTtable, not shown here).Super_ssn → Ssn(a supervisor’s SSN references an employee’s SSN).
Ssn → Fname, Minit, Lname, Bdate, Address, Sex, Salary, Super_ssn, Dno
Super_ssn → Ssn
Dno → Dname
Real-world tie:
- NEPSE’s stock trading system uses FDs to ensure each
Traderecord has a validStock(e.g.,StockCode → StockName) and a validTrader(e.g.,TraderID → TraderName). IfTraderIDis missing, the trade is invalid.
3. Relational Algebra: The 12 Operations
Relational algebra is a set-based language for querying tables. It does not use SQL syntax but is the foundation for query optimization.
Core Operations (5)
| Operation | Symbol | Description | Example |
|---|---|---|---|
| Select (σ) | σ | Filters tuples where a condition is true. | σ(Salary > 50000)(EMPLOYEE) |
| Project (π) | π | Returns specified columns (removes duplicates). | π(SName, Salary)(EMPLOYEE) |
| Cartesian Product (×) | × | Combines every tuple from table A with every tuple from table B. | EMPLOYEE × DEPARTMENT (useless without filtering!) |
| Union (∪) | ∪ | Merges two tables with identical schemas (removes duplicates). | π(SID)(ENROLLMENT_A) ∪ π(SID)(ENROLLMENT_B) |
| Set Difference (-) | - | Returns tuples in the first table but not the second. | EMPLOYEE - σ(Salary = 0)(EMPLOYEE) (remove zero-salary employees) |
Join Operations (5)
| Operation | Symbol | Description | Example |
|---|---|---|---|
| Natural Join (⋈) | ⋈ | Joins tables on common attributes (no explicit condition). | EMPLOYEE ⋈ DEPARTMENT (joins on Dno) |
| Theta Join (⋈ₚ) | ⋈ₚ | Joins tables where a condition ₚ is true. |
EMPLOYEE ⋈ₚ(Salary > 50000)(DEPARTMENT) (employees earning >50k) |
| Divide (÷) | ÷ | Returns tuples from table A where all matching tuples in table B exist. | EMPLOYEE ÷ π(Dno)(DEPARTMENT) (employees in all departments) |
| Intersection (∩) | ∩ | Returns tuples common to both tables. | π(SID)(ENROLLMENT_A) ∩ π(SID)(ENROLLMENT_B) |
| Assignment (=) | = | Renames a relation (used in expressions). | E → π(SID, CName)(EMPLOYEE ⋈ COURSE) |
Aggregation (2)
| Operation | Symbol | Description | Example |
|---|---|---|---|
| Aggregate (γ) | γ | Computes sums, averages, etc., grouped by attributes. | γ(Salary + 10000, Dno)(EMPLOYEE) (salary + bonus by department) |
| Division (÷) | ÷ | See above (also used for set division). | - |
| Operation | Symbol | Example | Output Description |
|----------------|--------|----------------------------------|---------------------------------------------|
| Select | σ | σ(Salary > 50k)(EMPLOYEE) | Employees earning >50k |
| Project | π | π(SName)(EMPLOYEE) | List of employee names |
| Natural Join | ⋈ | EMPLOYEE ⋈ DEPARTMENT | Employees with their department names |
Worked Example: Retrieving "John Smith’s" Department
Given:
EMPLOYEE(Ssn, Fname, Lname, Dno)DEPARTMENT(Dno, Dname)
Goal: Find Lname, Dno, Dname for "John Smith" (assuming Fname = "John", Lname = "Smith").
Steps:
Select John Smith’s records:
σ(Fname = "John" ∧ Lname = "Smith")(EMPLOYEE)Output:(Ssn=123, Fname=John, Lname=Smith, Dno=5)Join with
DEPARTMENT:(σ(Fname = "John" ∧ Lname = "Smith")(EMPLOYEE)) ⋈ DEPARTMENTOutput:| Ssn | Fname | Lname | Dno | Dname | |-----|-------|-------|-----|---------| | 123 | John | Smith | 5 | HR |
Real-world tie:
- Pathao’s driver assignment system uses a similar join to match drivers (
Driver) to available rides (Ride) based on location (Location). The query would be:σ(Location = "Kathmandu" ∧ Status = "Available")(Driver) ⋈ Ride
4. Relational Algebra vs. SQL
| Feature | Relational Algebra | SQL |
|---|---|---|
| Purpose | Theoretical foundation for query optimization. | Practical language for users. |
| Syntax | Uses symbols (σ, π, ⋈) and set notation. | Uses keywords (SELECT, FROM, JOIN). |
| Order of operations | Explicit (e.g., π(σ(...))). |
Implicit (e.g., SELECT ... FROM ... WHERE ...). |
| Example | π(SName)(σ(Salary > 50000)(EMPLOYEE)) |
SELECT SName FROM EMPLOYEE WHERE Salary > 50000; |
Why this matters:
- Google’s BigQuery uses relational algebra under the hood to optimize SQL queries before execution. For example, it might rewrite your SQL into a more efficient algebra expression.
5. Normalization: Avoiding Redundancy (Preview)
While not part of Unit 4, normalization is closely tied to relational algebra. Normal forms ensure data integrity by eliminating redundancy using FDs.
| Normal Form | Rule Violated (Before) | Example Fix |
|---|---|---|
| 1NF | Repeating groups or non-atomic values. | Split Orders into Order and Order_Items. |
| 2NF | Partial dependency (non-key attribute depends on part of PK). | Add a junction table for 1:N relationships. |
| 3NF | Transitive dependency (non-key attribute depends on another non-key attribute). | Move City from Student to a separate table. |
Example of 1NF Violation:
erDiagram
ORDERS {
int OrderID PK
string CustomerName
string Products[] // Repeating group (violates 1NF)
}
ORDERS_1NF {
int OrderID PK
string CustomerName
}
ORDER_ITEMS {
int OrderID FK
string ProductName
}1NF Violation (left) vs. Fixed (right) Fixed (2NF):
erDiagram
ORDERS {
int OrderID PK
string CustomerName
}
ORDER_ITEMS {
int OrderID FK
string ProductName
}Real-world tie:
- Khalti’s payment processing avoids redundancy by normalizing tables like
Transaction,User, andMerchantseparately. IfUserdata were duplicated in everyTransaction, updates (e.g., changing a user’s email) would require patching every record.
6. Exam Tip: How This Unit is Tested
SQL vs. Algebra:
- You may be given a relational algebra expression and asked to write the equivalent SQL (or vice versa).
- Example: Convert
π(SName, Salary)(σ(Salary > 50000)(EMPLOYEE))to SQL:SELECT SName, Salary FROM EMPLOYEE WHERE Salary > 50000;
Joins and FDs:
- Expect questions on how to map ER diagrams to relations, especially 1:N and N:M relationships.
- Example: Map
StudenttakesCourse(N:M) to a junction tableEnrollment(SID, CID, Grade).
Functional Dependencies:
- Given a table, identify all FDs and determine the closure of a set of attributes.
- Example: For
Student(SID, SName, City, Faculty), list all FDs and computeCity+ifFaculty → City.
Relational Algebra Queries:
- Solve problems using algebra operations (e.g., "Find all employees who earn more than their supervisor").
- Example:
Real-world Scenarios:
- Tie concepts to Nepali examples (e.g., "How would you model Pathao’s driver-ride matching using joins?").
- Example answer:
"Pathao uses a natural join between
Driver(withLocationandStatus) andRide(withLocationandRideID) to match available drivers to new rides. The join condition isDriver.Location = Ride.Location ∧ Driver.Status = "Available". This ensures only relevant drivers are considered."
Common Pitfalls:
- Cartesian products: Forgetting to filter after a cross join (e.g.,
EMPLOYEE × DEPARTMENTreturns 1000×20 = 20,000 rows!). - Duplicate tuples:
πremoves duplicates, butσdoes not. - Key constraints: Always check if a join preserves referential integrity (e.g., no orphaned
Enrollmentrecords).
- Cartesian products: Forgetting to filter after a cross join (e.g.,
Given:
EMPLOYEE(Ssn, Fname, Lname, Dno)
DEPARTMENT(Dno, Dname)
Find: Employee names and department names where the employee earns more than the department average salary.
Solution steps:
- Compute department average salary:
γ(AVG(Salary), Dno)(EMPLOYEE). - Join with
EMPLOYEEand filter:σ(Salary > γ(AVG(Salary), Dno)(EMPLOYEE).Salary)(EMPLOYEE ⋈ DEPARTMENT).
Final Summary Table
| Concept | Key Idea | Example |
|---|---|---|
| Relation | Table with PK, FK, and constraints. | Student(SID PK, SName, City) |
| Functional Dependency | X → Y if X determines Y. | SID → SName in Student. |
| Select (σ) | Filter rows. | σ(Credits > 3)(COURSE) |
| Project (π) | Return columns (remove duplicates). | π(SName)(EMPLOYEE) |
| Natural Join (⋈) | Join on common attributes. | EMPLOYEE ⋈ DEPARTMENT (on Dno) |
| Aggregation (γ) | Compute sums/averages by group. | γ(AVG(Salary), Dno)(EMPLOYEE) |
Exam Tip:
- Always assume tables are in 1NF unless told otherwise.
- Draw the tables when solving join problems—visualizing helps avoid Cartesian explosions.
- Practice converting SQL to algebra (and vice versa) to build intuition.
- For FD questions, list all obvious dependencies first (e.g., PK → all attributes).
Based on the TU BIT syllabus for Database Management System (BIT202), unit 4.
Discussion
Loading…