// free study notes

SQL aggregation & HAVING interview questions

GROUP BY questions look easy until the interviewer asks why your column is not in the GROUP BY. Worked answers for the whole family.

12 questions
  • 3 easy
  • 7 medium
  • 2 hard
Practice mode: all topics, shuffled

What this page covers

  • 12 questions on aggregation & HAVING, tagged easy, medium or hard, each with a worked answer in runnable SQL.
  • One schema throughout. The answers use the small shop schema shown here. Dialect-specific examples name the engine they are written for, and the few extra tables a question needs, such as subscribers or logins, are introduced where they appear.
  • Practice mode. To test yourself first, press Hide answers: each answer waits behind a Show answer button. The practice mode link deals a shuffled deck from every topic.
The shop schema
customers(customer_id, name, city, signup_date)
orders(order_id, customer_id, order_date, status, total)
order_items(order_id, product_id, quantity, unit_price)
products(product_id, name, category, price)
employees(employee_id, name, manager_id, department, salary, hired_on)

The questions

What is the difference between WHERE and HAVING?

Easy

WHERE filters rows before grouping; HAVING filters groups after aggregation. That is why aggregates can appear in HAVING but not in WHERE.

SELECT customer_id, SUM(total) AS spent
FROM orders
WHERE status = 'completed'          -- row filter, pre-aggregation
GROUP BY customer_id
HAVING SUM(total) >= 1000;          -- group filter, post-aggregation

Anchor the answer in the logical evaluation order: FROM, WHERE, GROUP BY, HAVING, SELECT, ORDER BY. WHERE cannot see aggregates because they do not exist yet when it runs.

What is the difference between COUNT(*), COUNT(column) and COUNT(DISTINCT column)?

Easy

COUNT(*) counts rows. COUNT(column) counts rows where that column is not NULL. COUNT(DISTINCT column) counts distinct non-NULL values.

SELECT COUNT(*)                        AS all_orders,
COUNT(discount_code)            AS orders_with_code,
COUNT(DISTINCT discount_code)   AS distinct_codes_used
FROM orders;

The interview trap is the second one: a report that meant all orders but wrote COUNT(shipped_at) quietly excludes unshipped rows. COUNT(*) is never slower than COUNT(column): the engine does not have to check any value for NULL and can scan the narrowest index. COUNT(1) is the same as COUNT(*) on every major engine.

Write total revenue per order status.

Easy

Group by the status column and sum the total. The GROUP BY columns define the grain: one output row per distinct status.

SELECT status, SUM(total) AS revenue, COUNT(*) AS order_count
FROM orders
GROUP BY status
ORDER BY revenue DESC;

Say the word grain out loud. Half of all aggregation questions are really about which grain the result is on, and whether the caller expects one row per status or one per status and date.

Return customers with more than five completed orders.

Mittel

Filter completed rows in WHERE, count per customer, keep big groups in HAVING.

SELECT customer_id, COUNT(*) AS completed_orders
FROM orders
WHERE status = 'completed'
GROUP BY customer_id
HAVING COUNT(*) > 5;

The follow-up: moving status = 'completed' into HAVING is an error, because status is neither grouped nor aggregated, so it has no single value per group. If you need both counts in one query, count conditionally instead: HAVING SUM(CASE WHEN status = 'completed' THEN 1 ELSE 0 END) > 5.

Filter groups by an aggregate that never appears in the SELECT list.

Mittel

HAVING can reference any aggregate, whether or not it is projected. Here the average order size drives the filter while only the count is shown.

SELECT customer_id, COUNT(*) AS order_count
FROM orders
GROUP BY customer_id
HAVING AVG(total) > 150;

If you also want the average visible, add AVG(total) to the SELECT list, but nothing requires it. Some candidates believe HAVING only works on SELECTed aggregates; it works on any aggregate over the group.

What does GROUP BY with multiple columns mean?

Mittel

One group per distinct combination of the listed columns, so the result grain is the pair. Revenue by status and month is one row per status and month.

-- PostgreSQL; see the next question for other engines:
SELECT DATE_TRUNC('month', order_date) AS month,
status,
SUM(total) AS revenue
FROM orders
GROUP BY DATE_TRUNC('month', order_date), status
ORDER BY month, status;

The pitfall to mention: every extra column multiplies the row count. GROUP BY month, status, customer_id returns one row per customer per status per month, and a dashboard that expected one row per month will show many. Always state the grain of a grouped result before writing it.

Group by month: why can you not just GROUP BY order_date, and what do you do instead?

Mittel

order_date has day-level grain, so grouping by it gives one group per day. You must group by an expression that collapses to the month, and then GROUP BY that same expression (or its alias where the engine allows it).

-- PostgreSQL / DuckDB:
SELECT DATE_TRUNC('month', order_date) AS month, SUM(total) AS revenue
FROM orders
GROUP BY 1
ORDER BY 1;

-- SQLite (dates stored as ISO text):
SELECT strftime('%Y-%m', order_date) AS month, SUM(total) AS revenue
FROM orders
GROUP BY month
ORDER BY month;

-- MySQL:
SELECT DATE_FORMAT(order_date, '%Y-%m') AS month, SUM(total) AS revenue
FROM orders
GROUP BY month
ORDER BY month;

-- SQL Server (DATETRUNC needs 2022+; use DATEFROMPARTS on older versions):
SELECT DATETRUNC(month, order_date) AS month, SUM(total) AS revenue
FROM orders
GROUP BY DATETRUNC(month, order_date)
ORDER BY month;

SQL Server accepts neither a SELECT alias nor an ordinal in GROUP BY, so the expression is repeated. PostgreSQL, MySQL and SQLite accept both. Ordinals break silently when someone reorders the SELECT list, so most style guides prefer the alias or the expression. Truncating to a date value rather than formatting to text also keeps the result sortable and usable in date arithmetic; FORMAT() on SQL Server is also notably slow per row.

Why does selecting a column that is not in GROUP BY fail?

Mittel

Because a group of several orders has several order_id values and the query gives no rule for which one to return. The standard (since SQL:1999) allows a non-grouped column only when it is functionally dependent on the grouped columns, meaning the GROUP BY columns determine it uniquely.

-- Errors on PostgreSQL, SQL Server, Oracle and MySQL 5.7+ (ONLY_FULL_GROUP_BY):
SELECT customer_id, order_id, SUM(total)
FROM orders
GROUP BY customer_id;

-- Allowed on PostgreSQL and MySQL: c.name depends on the grouped primary key
SELECT c.customer_id, c.name, SUM(o.total)
FROM customers c
JOIN orders o ON o.customer_id = c.customer_id
GROUP BY c.customer_id;

The fixes: add the column to GROUP BY, wrap it in an aggregate such as MAX(order_id), or use a window function when you need per-row detail next to group totals. SQL Server and Oracle do not apply the primary-key rule, so they need c.name in the GROUP BY too. SQLite, and MySQL with ONLY_FULL_GROUP_BY switched off, run the first query and return an arbitrary order_id per group, which is why MySQL turned that mode on by default in 5.7.

Count orders of each status in one pass over the table.

Hard

Conditional aggregation: SUM or COUNT a CASE inside one aggregate. One scan, one row, no self-joins.

SELECT COUNT(*)                                                  AS all_orders,
SUM(CASE WHEN status = 'completed' THEN 1 ELSE 0 END)     AS completed,
SUM(CASE WHEN status = 'cancelled' THEN 1 ELSE 0 END)     AS cancelled,
COUNT(*) FILTER (WHERE status = 'refunded')               AS refunded  -- PostgreSQL, SQLite
FROM orders;

The FILTER clause is the SQL-standard spelling of the same idea, supported by PostgreSQL, SQLite 3.30+ and DuckDB; SUM(CASE ...) works everywhere. COUNT(CASE WHEN status = 'completed' THEN 1 END) is a third form: with no ELSE, the CASE yields NULL and COUNT skips it. Add a GROUP BY and the same pattern gives per-customer or per-month status counts in one scan.

How do WHERE and HAVING interact in a query with a JOIN?

Mittel

JOINs run first, WHERE filters the joined rows, then grouping and HAVING apply. A filter placed before grouping changes what gets summed; placed in HAVING it filters whole groups.

-- Revenue from completed orders, customers who spent >= 1000:
SELECT c.name, SUM(o.total) AS spent
FROM customers c
JOIN orders o ON o.customer_id = c.customer_id
WHERE o.status = 'completed'
GROUP BY c.customer_id, c.name
HAVING SUM(o.total) >= 1000;

The subtle version they may ask next: moving o.status = 'completed' into HAVING fails because status is not grouped, and moving SUM(o.total) >= 1000 into WHERE fails because aggregates do not exist yet when WHERE runs. The evaluation order decides where each filter goes; style has nothing to do with it.

Group customers into spend buckets and count per bucket.

Hard

The tempting one-pass answer groups by a CASE over SUM(total), but that mixes grains: the bucket depends on an aggregate per customer, while the count is per bucket. One query cannot compute both in a single GROUP BY.

SELECT CASE
   WHEN spent >= 1000 THEN '1000+'
   WHEN spent >= 100  THEN '100-999'
   ELSE 'under 100'
END AS spend_bucket,
COUNT(*) AS customers
FROM (
SELECT customer_id, SUM(total) AS spent
FROM orders
GROUP BY customer_id
) per_customer
GROUP BY 1               -- SQL Server: repeat the CASE expression here
ORDER BY 1;

Recognizing that this needs two aggregation levels is the actual test. The inner query produces one row per customer, the outer one groups those rows into buckets. Customers with no orders are missing from both levels; if they should count as 'under 100', start the inner query from customers with a LEFT JOIN and COALESCE(SUM(o.total), 0).

How do you concatenate one column values per group, like all product names per order?

Mittel

String aggregation: STRING_AGG on PostgreSQL, SQL Server 2017+ and DuckDB, GROUP_CONCAT on MySQL and SQLite, LISTAGG on Oracle.

-- PostgreSQL / SQL Server:
SELECT o.order_id, STRING_AGG(p.name, ', ') AS products
FROM orders o
JOIN order_items oi ON oi.order_id = o.order_id
JOIN products p ON p.product_id = oi.product_id
GROUP BY o.order_id;

-- MySQL / SQLite: GROUP_CONCAT(p.name SEPARATOR ', ') / GROUP_CONCAT(p.name, ', ')

Mention ordering inside the aggregate, because without it the order of names is whatever the plan produced and can change between runs, which breaks comparisons and tests. The spelling differs: STRING_AGG(p.name, ', ' ORDER BY p.name) on PostgreSQL, STRING_AGG(p.name, ', ') WITHIN GROUP (ORDER BY p.name) on SQL Server, GROUP_CONCAT(p.name ORDER BY p.name SEPARATOR ', ') on MySQL. MySQL also truncates the result at group_concat_max_len, 1024 bytes by default, without an error.

Aggregation & HAVING interview FAQ

What is the difference between WHERE and HAVING?

WHERE filters rows before they are grouped; HAVING filters groups after aggregation. The worked questions show both sides of that line, including HAVING on an aggregate you never SELECT.

Do the answers cover COUNT(*) vs COUNT(column)?

Yes, including COUNT(DISTINCT ...), and the report that counts a nullable column and silently drops rows. The LEFT JOIN case, where COUNT(*) turns a customer with no orders into a count of 1, is on the joins page.

Are conditional aggregation and pivot questions included?

Yes. One question counts several statuses in a single pass with SUM(CASE ...), another groups customers into spend buckets defined with CASE inside GROUP BY.

Why does my non-aggregated column fail?

A dedicated question covers the functional-dependency rule behind ONLY_FULL_GROUP_BY in MySQL and the matching error in PostgreSQL and SQL Server, why grouping by a primary key lets you select the other columns of that table, and why SQLite accepts the query silently.

Other topics

// from study notes to daily tool

Now write some SQL against a real database

SQLly is a native SQL workbench for macOS, Windows and Linux: IntelliSense that knows your schema, a formatter, guardrails for risky queries, and every engine in one app.