works_on has 12 rows; one hours value (Gopal on CRM) is NULL and the other 11 add up to 220. Find COUNT(*), COUNT(hours), SUM(hours), AVG(hours) and AVG(COALESCE(hours, 0)).
Aggregate functions — COUNT, SUM, AVG, MIN, MAX — collapse many rows into one value; GROUP BY forms groups and HAVING filters them. NULL handling, the WHERE-versus-HAVING split and the grouping rules are among the most frequently asked SQL questions.
COUNT(*) counts rows; COUNT(col) counts non-NULL values; COUNT(DISTINCT col) counts distinct non-NULL values — so COUNT(*) ≥ COUNT(col) ≥ COUNT(DISTINCT col).AVG(col) = SUM(col) / COUNT(col), not SUM(col) / COUNT(*).An aggregate function takes the values of a column across many rows and returns a single summary value. Without GROUP BY, the whole table (after WHERE) is one group, so the query returns exactly one row. The five standard aggregates are COUNT, SUM, AVG, MIN and MAX.
SELECT COUNT(*) AS rows_, -- 10
COUNT(dept_id) AS with_dept, -- 9 (Jose's NULL skipped)
COUNT(DISTINCT dept_id) AS depts, -- 3 (10, 20, 30)
COUNT(DISTINCT manager_id) AS managers, -- 4 (101, 102, 103, 104)
SUM(salary) AS payroll, -- 430000
AVG(salary) AS avg_sal, -- 43000
MAX(salary), MIN(salary), -- 90000, 20000
MIN(ename), MAX(hire_date) -- 'Anil', '2023-11-02'
FROM emp;| Function | Works on | NULLs | Notes |
|---|---|---|---|
COUNT(*) | Rows | Counted (it counts rows, not values) | COUNT(1) behaves the same |
COUNT(col) | Any type | Ignored | Number of non-NULL values |
COUNT(DISTINCT col) | Any type | Ignored | Number of different non-NULL values |
SUM(col), AVG(col) | Numbers | Ignored | DISTINCT allowed: SUM(DISTINCT salary) adds each value once |
MIN(col), MAX(col) | Numbers, strings, dates | Ignored | Alphabetical for strings, chronological for dates |
DISTINCT inside an aggregate removes duplicate values before aggregating. On emp, SUM(salary) = 430000 but SUM(DISTINCT salary) = 380000, because the second 50000 (Divya and Eby earn the same) is added only once; likewise COUNT(DISTINCT salary) = 9 and AVG(DISTINCT salary) = 380000 / 9 = 42222.22, while COUNT(DISTINCT job) = 5. DISTINCT makes no difference to MIN and MAX.
Products add more: STDDEV and VARIANCE (Oracle, MySQL, PostgreSQL), string aggregation (GROUP_CONCAT in SQLite and MySQL, LISTAGG in Oracle, STRING_AGG in PostgreSQL and SQL Server) and SQLite's TOTAL, a SUM that returns 0.0 instead of NULL for no rows.
Gopal's hours on CRM are not yet recorded, so works_on has 12 rows but only 11 known hour values, adding up to 220. Because aggregates skip NULLs, the 'average hours' depends on what you divide by.
SELECT COUNT(*) AS rows_, -- 12
COUNT(hours) AS known, -- 11
SUM(hours) AS total, -- 220
AVG(hours) AS avg_known, -- 20 = 220 / 11
SUM(hours) * 1.0 / COUNT(*) AS per_row, -- 18.33 = 220 / 12
AVG(COALESCE(hours, 0)) AS null_as_zero -- 18.33
FROM works_on;Neither 20 nor 18.33 is 'wrong' — they answer different questions. AVG(hours) is the average of the known values; if a NULL should count as zero, say so with COALESCE. On exams, remember: AVG(col) = SUM(col) / COUNT(col).
| Query (department 40 has no employees) | Result |
|---|---|
SELECT COUNT(*) FROM emp WHERE dept_id = 40 | 0 |
SELECT COUNT(salary) FROM emp WHERE dept_id = 40 | 0 |
SELECT SUM(salary) FROM emp WHERE dept_id = 40 | NULL |
SELECT AVG(salary), MAX(salary) FROM emp WHERE dept_id = 40 | NULL, NULL |
SELECT dept_id, COUNT(*) FROM emp WHERE dept_id = 40 GROUP BY dept_id | no rows at all |
GROUP BY partitions the rows (after WHERE) into groups with equal values in the grouping columns and produces one output row per group. Rows whose grouping value is NULL form one group of their own — so Jose, the employee without a department, appears as a separate group.
SELECT dept_id, COUNT(*) AS n, SUM(salary) AS total, ROUND(AVG(salary), 2) AS avg_sal
FROM emp
GROUP BY dept_id;| dept_id | n | total | avg_sal |
|---|---|---|---|
| NULL | 1 | 25000 | 25000 |
| 10 | 2 | 112000 | 56000 |
| 20 | 4 | 180000 | 45000 |
| 30 | 3 | 113000 | 37666.67 |
The grouping rule: each item in the SELECT list must be a grouping column, an aggregate, a constant, or an expression built from these. SELECT dept_id, ename, COUNT(*) FROM emp GROUP BY dept_id is illegal in standard SQL — a department has many names, so which one should be shown? Oracle raises 'not a GROUP BY expression', PostgreSQL and SQL Server raise errors, MySQL rejects it under ONLY_FULL_GROUP_BY (the default since 5.7), but SQLite quietly picks one row's ename. Never rely on that.
Grouping by several columns makes a group for each distinct combination: GROUP BY dept_id, job yields 8 groups on the sample data — for instance (20, Analyst) with 2 employees and a total of 100000, and (30, Salesman) with 2 and 58000. You can also group by an expression, such as GROUP BY strftime('%Y', hire_date) to count hires per year. The GROUP BY columns need not appear in the SELECT list.
HAVING COUNT(*) >= 2SELECT dept_id, COUNT(*) AS n
FROM emp
WHERE job <> 'President' -- row filter: Anil removed first
GROUP BY dept_id
HAVING COUNT(*) >= 2; -- group filter
-- dept 10 keeps only Hari (1) → dropped; 20 → 4; 30 → 3; NULL group (Jose) → dropped
-- result: (20, 4), (30, 3)Aggregates may also appear in ORDER BY: SELECT job, COUNT(*) FROM emp GROUP BY job ORDER BY COUNT(*) DESC, job LIMIT 1 returns the most common job, Clerk (3). SELECT dept_id, AVG(salary) FROM emp GROUP BY dept_id HAVING AVG(salary) > 40000 returns departments 10 (56000) and 20 (45000). Putting the same condition in WHERE is an error, because averages do not exist until the groups are formed. A condition on a grouping column (HAVING dept_id = 20) is legal in HAVING but belongs in WHERE, where it shrinks the work earlier.
SELECT COUNT(*) FROM emp HAVING COUNT(*) > 5 is legal and returns 10 — HAVING may appear without GROUP BY. And … GROUP BY department WHERE salary > 50000 is a syntax error: WHERE must come before GROUP BY.Questions like 'the department with the highest average salary' need an aggregate of aggregates. Standard SQL forbids writing MAX(AVG(salary)) directly — SQLite reports 'misuse of aggregate function AVG()'. Compute the inner aggregate in a derived table or a HAVING sub-query instead.
-- 1. aggregate a derived table: the highest departmental average
SELECT MAX(avg_sal) FROM (SELECT AVG(salary) AS avg_sal FROM emp GROUP BY dept_id); -- 56000
-- 2. which department has it: compare each group with that maximum
SELECT dept_id, AVG(salary) AS avg_sal
FROM emp GROUP BY dept_id
HAVING AVG(salary) = (SELECT MAX(a) FROM (SELECT AVG(salary) AS a FROM emp GROUP BY dept_id));
-- 10 | 56000
-- 3. sort the groups and take the first (ties would be cut off)
SELECT dept_id, AVG(salary) AS avg_sal FROM emp GROUP BY dept_id ORDER BY avg_sal DESC LIMIT 1;
-- Oracle / PostgreSQL / SQL Server also allow: HAVING AVG(salary) >= ALL (SELECT AVG(salary) FROM emp GROUP BY dept_id)SELECT MAX(AVG(salary)) FROM emp GROUP BY dept_id (nesting depth two, only with GROUP BY). Exams that ask 'is MAX(AVG(x)) allowed?' expect the standard answer — no.| Question | Query | Result on the sample data |
|---|---|---|
| Employees per job, largest first | SELECT job, COUNT(*) AS n FROM emp GROUP BY job ORDER BY n DESC, job | Clerk 3, Analyst 2, Manager 2, Salesman 2, President 1 |
| Jobs paid above the company average | … GROUP BY job HAVING AVG(salary) > (SELECT AVG(salary) FROM emp) | Analyst 50000, Manager 57500, President 90000 |
| Employees on at least two projects | SELECT e.ename, COUNT(*) FROM emp e JOIN works_on w ON w.emp_id = e.emp_id GROUP BY e.emp_id, e.ename HAVING COUNT(*) >= 2 | Bindu 4, Eby 3, Divya 2 |
| Workers and hours per project | SELECT p.pname, COUNT(w.emp_id), SUM(w.hours) FROM project p LEFT JOIN works_on w ON w.proj_id = p.proj_id GROUP BY p.proj_id, p.pname | AI Lab 3/70, Payroll 3/60, CRM 3/50, Website 3/40 |
| Projects and budget per department, including none | SELECT d.dname, COUNT(p.proj_id), SUM(p.budget) FROM dept d LEFT JOIN project p ON p.dept_id = d.dept_id GROUP BY d.dept_id, d.dname | Accounts 1/400000, Research 2/1200000, Sales 1/500000, Operations 0/NULL |
| Staff list per department | SELECT dept_id, GROUP_CONCAT(ename, ', ') FROM emp GROUP BY dept_id | 20 → Bindu, Divya, Eby, Indu (SQLite/MySQL syntax) |
SELECT d.dname, SUM(e.salary) FROM dept d JOIN emp e ON e.dept_id = d.dept_id JOIN project p ON p.dept_id = d.dept_id WHERE d.dept_id = 20 GROUP BY d.dept_id pairs Research's 4 employees with its 2 projects — 8 rows — and reports a payroll of 360000, double the true 180000. Aggregate each child table separately (derived tables or scalar sub-queries) and then join the totals.Two details in that table repay attention. CRM's total is 50 even though Gopal's hours are NULL — SUM skips the NULL. And Operations shows 0 projects because COUNT(p.proj_id) counts the NULL-padded row of the outer join as nothing; COUNT(*) would have wrongly reported 1.
Reports often need subtotals and a grand total along with the detail groups. SQL:1999 added super-aggregate extensions to GROUP BY. They are supported by Oracle, SQL Server, PostgreSQL, DB2 and (ROLLUP only, written GROUP BY a, b WITH ROLLUP) MySQL — but not by SQLite, where you combine GROUP BY queries with UNION ALL.
| Clause | Grouping sets produced | Count for n columns |
|---|---|---|
GROUP BY ROLLUP(a, b) | (a, b), (a), () | n + 1 (hierarchical subtotals) |
GROUP BY CUBE(a, b) | (a, b), (a), (b), () | 2ⁿ (every combination) |
GROUP BY GROUPING SETS((a), (b)) | exactly the listed sets | as listed |
SELECT * FROM (
SELECT dept_id, job, SUM(salary) AS total FROM emp WHERE dept_id IN (20, 30) GROUP BY dept_id, job
UNION ALL
SELECT dept_id, NULL, SUM(salary) FROM emp WHERE dept_id IN (20, 30) GROUP BY dept_id
UNION ALL
SELECT NULL, NULL, SUM(salary) FROM emp WHERE dept_id IN (20, 30)
) ORDER BY dept_id IS NULL, dept_id, job IS NULL, job;
-- 20 Analyst 100000 | 20 Clerk 20000 | 20 Manager 60000 | 20 NULL 180000
-- 30 Manager 55000 | 30 Salesman 58000 | 30 NULL 113000 | NULL NULL 293000
-- Oracle/PostgreSQL: SELECT dept_id, job, SUM(salary) FROM emp WHERE dept_id IN (20, 30)
-- GROUP BY ROLLUP(dept_id, job);The NULLs in subtotal rows mean 'all values', not missing data. The GROUPING(col) function returns 1 when a NULL was produced by the rollup and 0 for a genuine NULL, so reports can label rows 'Total'.
A window function computes a value over a set of rows related to the current row — its window — without collapsing them into one. The syntax is function() OVER (PARTITION BY … ORDER BY …). Window functions arrived in SQL:2003 and are supported by Oracle (as 'analytic functions'), SQL Server, PostgreSQL, MySQL 8 and SQLite 3.25+.
SELECT ename, salary,
RANK() OVER (ORDER BY salary DESC) AS rnk,
DENSE_RANK() OVER (ORDER BY salary DESC) AS drnk,
ROW_NUMBER() OVER (ORDER BY salary DESC) AS rn
FROM emp;| ename | salary | RANK | DENSE_RANK | ROW_NUMBER |
|---|---|---|---|---|
| Anil | 90000 | 1 | 1 | 1 |
| Bindu | 60000 | 2 | 2 | 2 |
| Charles | 55000 | 3 | 3 | 3 |
| Divya | 50000 | 4 | 4 | 4 |
| Eby | 50000 | 4 | 4 | 5 |
| Fathima | 30000 | 6 | 5 | 6 |
| Gopal | 28000 | 7 | 6 | 7 |
Aggregates become window functions too: AVG(salary) OVER (PARTITION BY dept_id) prints each employee's department average beside their own salary (Bindu 60000 next to 45000), and SUM(salary) OVER (ORDER BY hire_date) gives a running total (90000, 150000, 205000, 255000 …). Wrapping a ranking in a derived table answers 'top earner per department': … WHERE r = 1 after RANK() OVER (PARTITION BY dept_id ORDER BY salary DESC) AS r returns Anil, Bindu and Charles.
Try the problem first, then reveal the working one step at a time.
works_on has 12 rows; one hours value (Gopal on CRM) is NULL and the other 11 add up to 220. Find COUNT(*), COUNT(hours), SUM(hours), AVG(hours) and AVG(COALESCE(hours, 0)).
Evaluate SELECT dept_id, ROUND(AVG(salary), 2) AS avg_sal FROM emp GROUP BY dept_id HAVING AVG(salary) > 40000; on the sample data.
Find the department whose average salary is highest, without using a nested aggregate such as MAX(AVG(salary)).
Using the ranking table in this topic, which function and value would you use to find (a) the 4th highest distinct salary, (b) the employee in 5th position for a paged list, (c) the competition-style position of Fathima?
Predict the output of SELECT COUNT(*), COUNT(manager_id), COUNT(DISTINCT manager_id) FROM emp; on the sample data.
Write a query listing each job whose average salary is higher than the overall average salary, and give the result.
What is wrong with SELECT dept_id, AVG(salary) FROM emp WHERE AVG(salary) > 40000 GROUP BY dept_id; and how is it fixed?
Department 40 controls no project. What do these return? (a) SELECT MAX(budget) FROM project WHERE dept_id = 40; (b) SELECT COUNT(budget) FROM project WHERE dept_id = 40; (c) SELECT dept_id, SUM(budget) FROM project WHERE dept_id = 40 GROUP BY dept_id;
How many grouping sets do GROUP BY ROLLUP(a, b, c) and GROUP BY CUBE(a, b, c) produce? List them for ROLLUP.
COUNT(col) skips NULLs while COUNT(*) does not; COUNT(DISTINCT col) skips NULLs and duplicates.AVG(col) ≠ SUM(col) / COUNT(*) when NULLs exist; wrap the column in COALESCE if NULL should count as zero.COUNT(*) counts the NULL-padded row as 1; count a column of the inner table to get 0.12 questions. 70 % passes the topic quiz (+30 XP, +20 more for 100 %). Exam scoring: +1 correct, −⅓ wrong.
Modelled on real KPSC questions (reworded) with the same concept and answer; each links to its original paper.