GROUP BY and Aggregation: SQL Interview Patterns

← Community · SQL·By Aman Raj·Published ·10 min read·1,211 words

Aggregation turns a table of rows into answers to questions: how many, how much, what average, which biggest. GROUP BY decides the grouping key, aggregate functions (COUNT, SUM, AVG, MIN, MAX) compute the summary, and HAVING filters the finished groups. These three pieces power most reporting SQL — and most SQL interview rounds.

The worked examples below use one invented sales table. Every expected result is shown, so you can solve on paper and verify.

The dataset

sale_idregionproductunitspricesale_date
1NorthPen10202026-11-02
2NorthPen5202026-11-03
3NorthBook31202026-11-03
4SouthPen8202026-11-04
5SouthBag24502026-11-04
6SouthBag14502026-11-05
7EastBook61202026-11-05
8NULLPen4202026-11-06

Two deliberate imperfections: region is NULL on sale 8 (NULLs form their own group), and products/regions repeat so grouping has visible effects.

Pattern 1 — One summary per group

Task: Total revenue per region. Revenue is units * price per row.
SELECT region,
       SUM(units * price) AS revenue
FROM sales
GROUP BY region;
Expected result (4 rows):
regionrevenue
North760
South1260
East720
NULL80

Workings: North = 10×20 + 5×20 + 3×120 = 760. South = 8×20 + 2×450 + 1×450 = 1260. East = 720. NULL-region row = 80.

Rule: every column in SELECT must be either inside an aggregate or listed in GROUP BY. SELECT region, product, SUM(...) with GROUP BY region alone is invalid in strict SQL — and wrong in intent.

Pattern 2 — Filter groups with HAVING

Task: Regions with revenue above 750, highest first.
SELECT region, SUM(units * price) AS revenue
FROM sales
GROUP BY region
HAVING SUM(units * price) > 750
ORDER BY revenue DESC;
Expected result (2 rows):
regionrevenue
South1260
North760

Order of execution matters and is asked in interviews: FROM → WHERE → GROUP BY → HAVING → SELECT → ORDER BY. That is why WHERE SUM(...) is a syntax error (no groups exist yet in WHERE) and why aliases defined in SELECT sometimes cannot be referenced in HAVING (depends on the engine; PostgreSQL allows the alias in ORDER BY, not in HAVING).

Pattern 3 — WHERE before GROUP BY (filter rows, not groups)

Task: Revenue per region, excluding NULL regions — using only November 4 or later.
SELECT region, SUM(units * price) AS revenue
FROM sales
WHERE region IS NOT NULL
  AND sale_date >= '2026-11-04'
GROUP BY region;
Expected result (2 rows): South = 1260, East = 720. North is gone (its rows are dated Nov 2-3), the NULL-region row is gone by the first filter.

Interview phrasing to recognise: "total X for rows where Y" → WHERE. "total X only for groups where the total exceeds Z" → HAVING.

Pattern 4 — COUNT variants and NULL behaviour

Task: Per region: number of rows, number of rows with a product, number of distinct products.
SELECT region,
       COUNT(*)            AS rows_in_group,
       COUNT(product)      AS rows_with_product,
       COUNT(DISTINCT product) AS distinct_products
FROM sales
GROUP BY region;
Expected result (4 rows):
regionrows_in_grouprows_with_productdistinct_products
North332
South332
East111
NULL111
COUNT(*) counts rows; COUNT(column) skips NULLs in that column; COUNT(DISTINCT column) removes duplicates first. If product had been NULL on sale 8, rows_with_product for that group would read 0 while rows_in_group stayed 1.

Pattern 5 — The duplicate hunt (most-asked interview question)

Task: Find products that sold in more than one region.
SELECT product
FROM sales
GROUP BY product
HAVING COUNT(DISTINCT region) > 1;
Expected result (2 rows): Pen (North, South, NULL-region group excluded from DISTINCT? No — COUNT(DISTINCT region) ignores NULL regions, so Pen counts North + South = 2) and Book (North, East).

Same skeleton answers "duplicate emails" (GROUP BY email HAVING COUNT(*) > 1), "customers with more than 3 orders", "departments with average salary above 50000". Learn the skeleton once:

SELECT key, AGG(...) AS metric
FROM t
GROUP BY key
HAVING AGG(...) <condition>;

Pattern 6 — Top N per group (window functions)

Task: The top 2 products by revenue in each region.
WITH ranked AS (
  SELECT region,
         product,
         SUM(units * price) AS revenue,
         ROW_NUMBER() OVER (
           PARTITION BY region
           ORDER BY SUM(units * price) DESC
         ) AS rn
  FROM sales
  WHERE region IS NOT NULL
  GROUP BY region, product
)
SELECT region, product, revenue
FROM ranked
WHERE rn <= 2;
Expected result (5 rows): North — Pen (500), Book (360); South — Bag (1350), Pen (160); East — Book (720). GROUP BY collapses to region+product; ROW_NUMBER() ranks inside each region without collapsing further.

If an interviewer says "top N per group", they are usually testing whether you reach for a window function rather than nesting aggregates.

Aggregation cheat sheet

ExpressionBehaviour with NULLsTypical use
COUNT(*)Counts NULL rows tooRow counts
COUNT(col)Skips NULLs"How many have this filled in?"
SUM(col)NULL contributes nothing; all-NULL group → NULLTotals
AVG(col)Divides by non-NULL countAverages (beware skew!)
MIN / MAXSkips NULLsExtremes
GROUPING/GROUPING SETSEngine-specific rollupSubtotals (PostgreSQL ROLLUP, CUBE)

One behaviour that catches people: a group of all-NULL values gives SUM = NULL, not 0. Wrap with COALESCE(SUM(x), 0) when your report must show zero.

Common mistakes to avoid

  • Using WHERE for aggregate conditions — WHERE COUNT(*) > 2 is invalid; that is HAVING's job.
  • Mixing levels in SELECT — every non-aggregated column belongs in GROUP BY. SELECT region, product, SUM(units) with GROUP BY region fails (or worse, succeeds in non-strict engines and returns an arbitrary product).
  • Assuming AVG is the mean of the column as displayed — NULL-skipping changes the denominator. Know which metric you are reporting.
  • Forgetting ORDER BY stability — ties in "top" queries need a deterministic tiebreaker in ORDER BY, or results flap between runs.
  • GROUP BY on the wrong key — grouping by sale_date when the question says "per region" gives one row per date, not per region. Re-read the question's grouping noun.

Practice on PixoQuest

Aggregation is pattern recognition under time pressure: read the question, name the grouping key, choose the aggregate, decide WHERE vs HAVING. The PixoQuest SQL Basic course trains exactly that loop in short interactive quizzes — joins and aggregation included — with no setup. Run one quiz round before you sit down with a real engine, then type the six patterns above until they come out of your fingers.

Bottom line

GROUP BY picks the key, aggregates summarise each group, WHERE filters rows first and HAVING filters groups after. On our 8-row dataset, four patterns cover most interview questions: per-group totals, HAVING thresholds, duplicate hunts with HAVING COUNT(*) > 1, and top-N-per-group via ROW_NUMBER(). Know how NULLs bend COUNT, AVG, and SUM — that is where interview answers quietly separate.

Sources & further reading

  • PostgreSQL documentation, Tutorial: Aggregates: https://www.postgresql.org/docs/current/tutorial-agg.html
  • PostgreSQL documentation, Aggregate Functions (COUNT/SUM/AVG and NULL behaviour): https://www.postgresql.org/docs/current/functions-aggregate.html
  • PostgreSQL documentation, Window Functions (ROW_NUMBER, PARTITION BY): https://www.postgresql.org/docs/current/tutorial-window.html
  • PostgreSQL documentation, SELECT — clause execution order: https://www.postgresql.org/docs/current/sql-select.html

The table and expected results in this article are invented example data written for this exercise; no real sales or production data is used.

Frequently asked questions

What is the difference between WHERE and HAVING?

WHERE filters individual rows before grouping; HAVING filters groups after aggregation. WHERE cannot use aggregate functions (WHERE SUM(x) > 5 is invalid); HAVING can. The database executes FROM → WHERE → GROUP BY → HAVING → SELECT → ORDER BY.

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

COUNT(*) counts rows, including rows where the column is NULL. COUNT(column) counts only rows where that column is non-NULL. If a column has 2 NULLs in a 10-row group, COUNT(*) = 10 and COUNT(column) = 8.

Does AVG ignore NULLs?

Yes. AVG divides by the number of non-NULL values, not by the row count. For a group with values 10, 20, and NULL, AVG = 15. Use COALESCE(column, 0) if you want NULL counted as zero — but know that this changes the meaning of the metric.

How do I find duplicate values in a table?

GROUP BY the column and filter with HAVING COUNT(*) > 1: SELECT name, COUNT(*) FROM users GROUP BY name HAVING COUNT(*) > 1. This is one of the most repeated SQL interview questions.

How do I get the top N rows per group (e.g. top 2 products per region)?

Use a window function: ROW_NUMBER() OVER (PARTITION BY region ORDER BY units DESC) computed in a subquery or CTE, then filter rn <= 2. Plain GROUP BY aggregates the whole group and cannot rank inside it.

SQLGROUP BYaggregationSQL interviewHAVING

Published under the PixoQuest editorial policy.