Interview Q&A · SQL · 14 questions in this topic

Aggregations & GROUP BY — SQL Interview Q&A

All SQL topics

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

Example.sqlsql
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

Example.sqlsql
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

Example.sqlsql
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.

Recommended resourcesAffiliate links · may earn us a commission

Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits