Interview Q&A · SQL · 14 questions in this topic
Aggregations & GROUP BY — SQL Interview Q&A
Summarizing data — aggregate functions, grouping, HAVING, and the NULL semantics that skew reports. Part of Aggregations & GROUP BY · 192 questions in the SQL bank.
What do COUNT, SUM, AVG, MIN, MAX do?
Answer
COUNT tallies (COUNT(*) rows, COUNT(col) non-NULL values), SUM/AVG total and average numerics, MIN/MAX take extremes of any orderable type. All except COUNT(*) ignore NULLs — AVG over sparse data divides by the non-NULL count, not the row count.
Know each function's NULL rule and you avoid the classic reporting skew.
Example
SELECT COUNT(*) AS headcount, AVG(salary) AS mean_pay, -- NULL salaries excluded MAX(salary) AS top_pay FROM employees;
How does GROUP BY work? What must SELECT contain?
Answer
GROUP BY collapses rows sharing key values into one output row per group; SELECT may then contain only grouping keys and aggregates over the group (bare non-grouped columns are illegal in standard SQL — MySQL's lax mode picks arbitrary values). Filtering groups happens in HAVING, not WHERE.
Think split (GROUP BY) → apply (aggregates) → combine (result rows).
Example
SELECT department, COUNT(*) AS n, AVG(salary) AS avg_pay FROM employees GROUP BY department;
How do you aggregate conditionally (pivots without PIVOT)?
Answer
CASE inside aggregates (SUM(CASE WHEN ... THEN 1 ELSE 0 END)) computes per-category counts/sums in one pass — portable pivoting without vendor PIVOT syntax. FILTER (WHERE ...) (PostgreSQL/SQLite) is the cleaner standard form.
One grouped scan replaces N separate queries — the performance story as well as the style one.
Example
SELECT COUNT(*) FILTER (WHERE department = 'Engineering') AS eng, COUNT(*) FILTER (WHERE department = 'Sales') AS sales FROM employees;
💡 FILTER is the modern form; CASE-in-aggregate is the portable fallback — name both.
How do you find duplicates with GROUP BY + HAVING?
Answer
Group by the candidate key and keep groups with COUNT(*) > 1 — the duplicate detector. HAVING filters post-aggregation (WHERE cannot see counts). Extend to multi-column keys for composite dupes.
This pattern doubles as a data-quality audit for supposed-unique columns.
Example
SELECT email, COUNT(*) AS n FROM users GROUP BY email HAVING COUNT(*) > 1; -- every duplicated email
How do you compute percentages and ratios per group?
Answer
Divide a conditional aggregate by the group total (cast to decimal first — integer division truncates), or use window ratios (value / SUM(value) OVER ()) for row-level shares. Multiply by 100.0 for percents.
The cast-before-divide is load-bearing: integer/integer truncates to 0 in most engines.
Example
SELECT department, COUNT(*) * 100.0 / SUM(COUNT(*)) OVER () AS pct FROM employees GROUP BY department;
What is the difference between `WHERE` and `HAVING` (revisited with aggregates)?
Answer
WHERE trims input rows before grouping (cheap, index-friendly); HAVING trims output groups after aggregation. Aggregates belong in HAVING (or SELECT), never in WHERE. Pushing selective predicates to WHERE shrinks the grouping work.
Performance reading: WHERE reduces rows grouped; HAVING reduces groups returned.
Example
SELECT department, AVG(salary) FROM employees WHERE age > 25 -- before: fewer rows grouped GROUP BY department HAVING AVG(salary) > 60000; -- after: fewer groups kept
How do GROUP BY and DISTINCT relate?
Answer
GROUP BY without aggregates behaves like DISTINCT over the key columns — both collapse duplicates. DISTINCT is the dedup statement; GROUP BY is the summarization framework. COUNT(DISTINCT x) merges both: distinct values counted.
Use DISTINCT for unique lists, GROUP BY for per-group math.
Example
SELECT department FROM employees GROUP BY department; -- equivalent to: SELECT DISTINCT department FROM employees;
How do you get top-N per group (greatest-N-per-group)?
Answer
Window ROW_NUMBER() partitioned by group ordered by rank, filtered to rn <= N in an outer query — portable and flexible. Correlated-subquery COUNT (rows greater than me < N) works without windows. LATERAL (PostgreSQL) joins each group to its own LIMITed subquery efficiently.
ROW_NUMBER-partition-filter is the pattern to memorize; it generalizes to dedup, latest-per-user, and leaderboards.
Example
SELECT * FROM ( SELECT *, ROW_NUMBER() OVER ( PARTITION BY department ORDER BY salary DESC) AS rn FROM employees) t WHERE rn <= 3; -- top 3 per dept
💡 Partition-rank-filter is the greatest-N-per-group mantra.
How do NULLs interact with GROUP BY and aggregates?
Answer
GROUP BY collects all NULL keys into one group. COUNT(*) counts NULL rows; COUNT(col)/SUM/AVG skip NULLs. GROUP_CONCAT/STRING_AGG skip NULLs too. Empty-set aggregates return NULL (SUM of nothing) except COUNT (0).
Reports over sparse columns must decide: exclude (default), COALESCE to 0, or count separately.
Example
SELECT department, COUNT(*), COUNT(bonus), AVG(bonus) FROM employees GROUP BY department; -- NULL department forms its own group!
What are ROLLUP, CUBE and GROUPING SETS?
Answer
Extensions producing subtotals in one scan: ROLLUP gives hierarchical totals (dept, then grand), CUBE gives all combinations, GROUPING SETS lists exact groupings wanted. NULLs in super-aggregate rows are identified with GROUPING() (real NULL vs total NULL).
One pass with subtotals beats UNIONing multiple GROUP BYs.
Example
SELECT department, COUNT(*) FROM employees GROUP BY ROLLUP (department); -- per-dept rows + grand total
How do you compute running totals without window functions?
Answer
Correlated subquery (SUM of rows <= me) — correct, O(n²)-ish. Self-join on inequality — same shape. Window SUM() OVER (ORDER BY ...) is the real answer (single pass); these fallbacks matter for engines or interview constraints without windows.
Know the fallbacks, recommend the window — that ordering shows judgment.
Example
-- portable fallback: SELECT e1.id, (SELECT SUM(e2.salary) FROM employees e2 WHERE e2.id <= e1.id) AS running FROM employees e1;
How do you compute median / mode / percentiles in SQL?
Answer
Median: PERCENTILE_CONT(0.5) ordered-set aggregate (PostgreSQL) or AVG of middle rows via ROW_NUMBER math. Mode: GROUP BY value ORDER BY COUNT(*) DESC LIMIT 1. Percentiles: PERCENTILE_CONT/DISC or NTILE buckets.
AVG is not a median substitute on skewed data (salaries!) — interviewers probe exactly this confusion.
Example
-- PostgreSQL median: SELECT PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY salary) FROM employees;
💡 Mean vs median on skewed pay data is the judgment point behind the syntax.
How do you aggregate strings (GROUP_CONCAT / STRING_AGG / LISTAGG)?
Answer
STRING_AGG (PostgreSQL/SQL Server) / GROUP_CONCAT (MySQL/SQLite) / LISTAGG (Oracle) concatenate group values with a delimiter, usually with internal ORDER BY. NULLs are skipped. Length limits (group_concat_max_len in MySQL) truncate silently — check them.
Denormalized lists for display; never for storage (1NF says atomic values).
Example
SELECT department, STRING_AGG(name, ', ' ORDER BY name) AS roster FROM employees GROUP BY department;
How do you compare each row to its group average (above-average earners)?
Answer
HAVING-free approach: window AVG() OVER (PARTITION BY dept) beside each row, filter outside (windows cannot appear in WHERE). Or self-join group averages back. The window form is one scan and keeps row detail.
Windows compute alongside rows; GROUP BY collapses them — choosing correctly is the skill.
Example
SELECT * FROM ( SELECT *, AVG(salary) OVER (PARTITION BY department) AS dept_avg FROM employees) t WHERE salary > dept_avg;
Recommended resourcesAffiliate links · may earn us a commission