19.1 KB · commit 40bb182
← Previous: T05.3: Basic SQL Query Clauses (DISTINCT, ORDER BY, AS, LIKE) | 🏠 Index | Next: T05.5a: GROUP BY and HAVING Clauses →
Topic: T05 — SQL (DDL, DML, Aggregates, Subqueries) | Priority: 🟡 | Exam Frequency: 2/7 finals (7 marks) Sources: Silberschatz 7e Ch. 3 (§3.7, pp. 91–98) · Lecture Deck 03 (Slides 30–31) · Classnote by Raidah (p. 2) · Handnote by Fahim (p. 43)
Aggregate functions convert a collection of row values into a single summary value. They power all numeric calculations and analytical summaries in database queries. RUET final exams test both standard theoretical definitions (2019 Q.8(a)) and concrete calculation queries (2024 Q.7(a)). Understanding duplicate retention and NULL handling is essential to avoid common exam traps.
Aggregate Function: An aggregate function takes a collection of values from multiple rows as input and returns a single summary value. The five standard SQL aggregate functions are
COUNT,SUM,AVG,MIN, andMAX. By default, they keep duplicate values unless you writeDISTINCTinside the parentheses.
Null Value Handling in Aggregation: Every SQL aggregate function except
COUNT(*)ignoresNULLvalues in its input column before calculating the result. In contrast,COUNT(*)counts total rows regardless of whether individual columns containNULL.
Empty Collection Rule: When an input column has no rows or contains only
NULLvalues,COUNTreturns0. All other aggregate functions (SUM,AVG,MIN, andMAX) returnNULLon an empty or all-null input.
SQL provides five primary built-in aggregate functions. Each function operates on a column multiset:
| Function | Mathematical Purpose | Supported Data Types | Treatment of Duplicates | Example Query |
|---|---|---|---|---|
AVG([DISTINCT] A) | Arithmetic mean of values | Numeric only (INT, DECIMAL, FLOAT) | Retains duplicates by default; drops duplicates if DISTINCT specified | SELECT AVG(salary) FROM instructor; |
SUM([DISTINCT] A) | Arithmetic sum of values | Numeric only (INT, DECIMAL, FLOAT) | Retains duplicates by default; drops duplicates if DISTINCT specified | SELECT SUM(salary) FROM instructor; |
MIN([DISTINCT] A) | Minimum (lowest) value | Any ordered type (numeric, string, date) | DISTINCT allowed but produces the same result | SELECT MIN(salary) FROM instructor; |
MAX([DISTINCT] A) | Maximum (highest) value | Any ordered type (numeric, string, date) | DISTINCT allowed but produces the same result | SELECT MAX(salary) FROM instructor; |
COUNT([DISTINCT] A) | Count of non-null values | Any data type | Counts all non-null entries; counts unique entries if DISTINCT specified | SELECT COUNT(ID) FROM instructor; |
COUNT(*) | Count of total rows | Whole relation (tuples) | Counts every row, including rows with all null attributes | SELECT COUNT(*) FROM instructor; |
COUNT Variations and DistinctionsThe COUNT function works in three slightly different ways depending on what you pass inside its parentheses:
COUNT(*):
WHERE filter, regardless of what is inside the columns.NULL values.DISTINCT here (COUNT(DISTINCT *) triggers a syntax error).COUNT(attribute):
NULL.COUNT(DISTINCT attribute):
NULL entries, removes duplicate values, and counts only the unique values left over.-- Count total course sections offered in Spring 2018
SELECT COUNT(*)
FROM teaches
WHERE semester = 'Spring' AND year = 2018;
-- Count total distinct instructors teaching in Spring 2018
SELECT COUNT(DISTINCT ID)
FROM teaches
WHERE semester = 'Spring' AND year = 2018;
SUM and AVG: Duplicate Retention RuleUnlike set operations that strip out duplicates, SUM and AVG must keep duplicate numbers by default so the math stays accurate. For instance, suppose a department has three instructors earning $75,000, $75,000, and $90,000. The true total payroll is:
Dividing that total by all 3 instructors gives the true average salary:
Average Salary=3240000=80000If you wrote AVG(DISTINCT salary) instead, SQL would throw away the second $75,000 salary before averaging:
Because of this, ALL is always the default inside SUM and AVG. Never put DISTINCT inside SUM or AVG unless an exam question specifically asks for the sum or average of distinct values.
MIN and MAX: Non-Numeric TypesWhile SUM and AVG only make sense for numbers, MIN and MAX work on any data type that has a natural sorting order:
MIN(salary) finds the smallest salary).'Ahmed' comes before 'Zaman'.MIN(order_date) gives the earliest date and MAX(order_date) gives the latest date.NULL values can easily trip you up in aggregate queries if you do not keep two simple rules in mind.
The Ignore Rule:
Every column-level aggregate function (SUM, AVG, MIN, MAX, and COUNT(col)) completely skips NULL values before doing the math. Only COUNT(*) includes rows with NULLs because it counts rows rather than column values.
The Empty Set Rule:
If a table has zero matching rows, or if every single value in the target column is NULL:
COUNT returns 0.SUM, AVG, MIN, and MAX return NULL (not 0!).Suppose a relation EMPLOYEE has four rows:
| EID | Name | Salary |
|---|---|---|
| E01 | Alice | 50000 |
| E02 | Bob | NULL |
| E03 | Carol | 70000 |
| E04 | David | NULL |
The aggregate queries evaluate as follows:
| Query Expression | Evaluated Set | Result | Reason |
|---|---|---|---|
COUNT(*) | 4 rows | 4 | Counts all physical rows |
COUNT(Salary) | {50000, 70000} | 2 | Skips both NULL values |
SUM(Salary) | 50000 + 70000 | 120000 | Ignores NULL entries |
AVG(Salary) | 120000 / 2 | 60000 | Divides by count of non-null values (n=2) |
MIN(Salary) | {50000, 70000} | 50000 | Smallest non-null number |
MAX(Salary) | {50000, 70000} | 70000 | Largest non-null number |
In relational algebra, we cannot express sums or averages using only basic operators like σ or Π. Instead, SQL aggregation corresponds to the extended relational algebra aggregation operator γ (sometimes written as calligraphic G). Intuitively, γ groups rows by a list of attributes on the left subscript and computes summary functions on the right subscript:
GγF(E)Where:
avg, sum, count, min, max) applied to specific columns.For example, the SQL query:
SELECT AVG(salary) AS avg_sal
FROM instructor;
Maps directly to this relational algebra expression:
γavg(salary) as avg_sal(instructor)The table below summarizes all past semester final questions on aggregate function theory and simple calculation:
| Year & Question | Marks | Format | Core Tested Concept |
|---|---|---|---|
| 2019 Q.8(a) | 4 | Theory discussion | Definition of aggregate functions; detailed review of four standard functions (COUNT, SUM, AVG, MIN/MAX) with examples. |
| 2024 Q.7(a) | 3 | Definition + SQL Query | Formal definition of aggregated functions; department total salary calculation query using SUM and GROUP BY; identifying SALES as a decoy table. |
Appeared: 2019 Q.8(a) — (04 Marks)
Question:
Discuss about four aggregate functions.
Full Answer:
An aggregate function in SQL takes a collection (a set or multiset) of values from a column of a relation and computes a single summarizing scalar value. SQL automatically ignores null values during aggregation (except in COUNT(*)).
Four standard aggregate functions are:
COUNT() FunctionCOUNT(*): Returns the total number of rows matching the query condition, including duplicate rows and rows with NULL values.COUNT(attribute): Returns the number of tuples with non-null values for the specified attribute.COUNT(DISTINCT attribute): Returns the count of unique, non-null values.SELECT COUNT(*) AS total_instructors
FROM instructor;
SUM() FunctionINT, FLOAT, DECIMAL).NULL if the relation is empty.SELECT SUM(salary) AS total_payroll
FROM instructor;
AVG() FunctionSELECT AVG(salary) AS avg_cs_salary
FROM instructor
WHERE dept_name = 'Comp. Sci.';
MIN() and MAX() FunctionsMIN() returns the lowest value in a column, while MAX() returns the highest value.SELECT MIN(salary) AS lowest_salary,
MAX(salary) AS highest_salary
FROM instructor;
Appeared: 2024 Q.7(a) — (03 Marks | Sec B | CO1)
Question:
Define aggregated functions.
EMPLOYEE (EID, Name, Department, Salary)
SALES (SID, EID, SaleAmount, SaleDate)
The management wants to reward the top-earing department. Write a SQL query to find the total salary paid per department.
(Note: "top-earing" printed verbatim in original paper; refers to top-earning)
Full Answer:
An aggregate function is a built-in SQL function that takes a collection (multiset) of values from a column across multiple tuples (or subsets partitioned by a GROUP BY clause) and returns a single summarizing scalar value. The five standard aggregate functions defined in SQL are AVG, MIN, MAX, SUM, and COUNT.
EMPLOYEE (EID, Name, Department, Salary): Contains the department name and employee salary.SALES (SID, EID, SaleAmount, SaleDate): Contains individual sales transactions.Department and Salary) reside entirely within the EMPLOYEE table. The SALES relation is an extraneous decoy table provided in the prompt and must not be joined. Joining SALES would multiply employee rows by their sales count, distorting the total salary sum.SELECT Department,
SUM(Salary) AS Total_Salary
FROM EMPLOYEE
GROUP BY Department;
Assume the EMPLOYEE table contains the following records:
| EID | Name | Department | Salary |
|---|---|---|---|
| 101 | Hasan | ECE | 60000 |
| 102 | Rafiq | CSE | 70000 |
| 103 | Tania | ECE | 65000 |
| 104 | Sohel | EEE | 55000 |
GROUP BY Department: Forms three distinct department groups:
'ECE': Salaries {60000, 65000}'CSE': Salaries {70000}'EEE': Salaries {55000}SUM(Salary): Calculates the total for each group:
'ECE': 60000+65000=125000'CSE': 70000'EEE': 55000| Department | Total_Salary |
|---|---|
| ECE | 125000 |
| CSE | 70000 |
| EEE | 55000 |
Source: Silberschatz 7e · Chapter 3 (Exercise 3.30)
Exam Relevance: High-Probability SQL Aggregation Theory & Edge-Case Drill
Key Tested Concept: Divergence between AVG(A) and COUNT(∗)SUM(A), null-value ignoring behavior, and empty relation semantics.
Problem Statement:
Consider the following SQL query on the university schema:
SELECT AVG(salary) - (SUM(salary) / COUNT(*)) FROM instructor;We might expect that the result of this query is zero (0) since the average of a set of numbers is mathematically defined as the sum of the numbers divided by the count of numbers. Indeed, this holds true for relation instances where every tuple contains a valid, non-null salary. However, there are possible relation instances of
instructorfor which the result is not zero (or does not evaluate to 0).
- Provide an instance of the relation for which the result is not zero, and explain formally why the result is non-zero.
- Explain what occurs if the
instructorrelation is completely empty (0 tuples).
Model Exam-Style Solution:
Relation Instance with Non-Zero Result: The NULL Attribute Trap
Sample Instance of instructor:
Suppose the instructor table contains three tuples:
| ID | name | dept_name | salary |
|---|---|---|---|
| 10101 | Srinivasan | Comp. Sci. | 65000 |
| 12121 | Wu | Finance | 90000 |
| 15151 | Mozart | Music | NULL |
Evaluation of AVG(salary):
COUNT(*)) strictly ignore NULL values in their input collection.AVG(salary) computes the mean over only the non-null salaries {65000,90000}:
AVG(salary)=265000+90000=2155000=77500
Evaluation of SUM(salary) / COUNT(*):
SUM(salary) ignores NULL and computes the sum of non-null salaries:
SUM(salary)=65000+90000=155000
COUNT(*) counts all tuples in the relation, regardless of whether any column contains NULL:
COUNT(∗)=3
Result of the Expression:
Result=77500−51666.67=25833.33=0Conclusion: Whenever an attribute contains at least one NULL value alongside non-null values, COUNT(∗)>COUNT(A), causing AVG(A)>COUNT(∗)SUM(A). The query evaluates to a positive non-zero value.
The Empty Relation Edge Case (0 Tuples):
instructor relation is empty (contains 0 tuples).COUNT(*) evaluates to 0.SUM(salary) evaluates to NULL.AVG(salary) evaluates to NULL.SUM(salary) / COUNT(*) evaluates to NULL / 0. In SQL arithmetic, dividing NULL by any number (or division by zero) produces NULL (or raises a division-by-zero runtime error depending on engine settings).NULL - NULL = NULL.NULL is an unknown/undefined value, not zero (0). Thus, the query does not return 0.💡 RUET Exam Takeaway:
Always emphasize the fundamental asymmetry in SQL: COUNT(*) counts rows (including NULLs), whereas all other aggregate functions (AVG, SUM, MIN, MAX, COUNT(A)) discard NULL values before computation. On an empty table, COUNT(*) returns 0, while all other aggregates return NULL.
EMPLOYEE and SALES), inspect which table actually holds the target attributes. Joining SALES in 2024 Q.7(a) duplicates salary values whenever an employee makes multiple sales.COUNT(*) vs COUNT(A): Always state that COUNT(*) counts all rows including NULLs, whereas COUNT(A) counts only non-null values of attribute A.0 for COUNT(*), but returns NULL for SUM, AVG, MIN, and MAX.SUM() or AVG() to character strings or dates. MIN() and MAX() work on strings and dates.AS: Raw aggregate outputs produce database-generated column headers like avg(salary). Always assign meaningful aliases like AS avg_salary.← Previous: T05.3: Basic SQL Query Clauses (DISTINCT, ORDER BY, AS, LIKE) | 🏠 Index | Next: T05.5a: GROUP BY and HAVING Clauses →