Sub topic 8
Grouping and Aggregation in Relational Algebra
Assume you know relations, tuples, selection, projection, joins, and basic set operations. This chapter uses extended relational algebra, which adds grouping and aggregate functions to classical relational algebra.
Grouping and aggregation in relational algebra
Classical relational algebra returns relations by applying operators such as selection and projection. It does not directly count rows or calculate averages. Extended relational algebra uses the grouping operator, commonly written as γ (gamma).
A grouping expression has this form:
γ_grouping_attributes; aggregate_functions (Relation)For example, suppose:
Enrolled(sid, cid, marks)To count the students enrolled in each course:
γ_cid; COUNT(sid) → number_of_students (Enrolled)The result has one tuple per distinct cid.
| cid | number_of_students |
|---|---|
| 10 | 3 |
Common aggregate functions are COUNT, SUM, AVG, MIN, and MAX.
To find the average marks in each course:
γ_cid; AVG(marks) → average_marks (Enrolled)To group by more than one attribute, list the attributes together:
γ_dept, year; COUNT(sid) → student_count (Student)This creates one group for every distinct (dept, year) pair.
Grouping usually comes after filtering. If only marks of at least 40 should be counted, first apply selection:
γ_cid; COUNT(sid) → passed_count
(σ_marks ≥ 40 (Enrolled))The order matters. Filtering before grouping changes which tuples enter each group.
Writing queries in relational algebra
Translate an English query by identifying the required steps:
- Choose the relation or join the needed relations.
- Filter tuples with selection.
- Combine relations with a join or set operation.
- Group and aggregate if required.
- Keep only the requested attributes with projection.
Consider:
Student(sid, sname, age)
Enrolled(sid, cid, marks)To find the names of students older than 20:
π_sname (σ_age > 20 (Student))To find the IDs of students who scored at least 80 in course 10:
π_sid (
σ_cid = 10 ∧ marks ≥ 80 (Enrolled)
)To find the names of those students, join the result with Student:
π_sname (
Student ⋈_{Student.sid = Enrolled.sid}
σ_cid = 10 ∧ marks ≥ 80 (Enrolled)
)To find courses with at least 10 enrollments:
π_cid (
σ_number_of_students ≥ 10 (
γ_cid; COUNT(sid) → number_of_students (Enrolled)
)
)The selection on number_of_students occurs after grouping because it filters groups, not individual enrollment tuples. This corresponds to SQL's HAVING clause.
Exercise
Write an extended relational algebra expression that returns each course ID and its highest mark from Enrolled(sid, cid, marks).
Show answer
γcid; MAX(marks) → highestmark (Enrolled)