Skip to the solution
MediumDSA13 min read

How does GROUP BY work with aggregate functions?

1.1k views

The problem

Question presented to candidate: "Given a sales table and a reps table, show revenue per product and per region per month. Then explain what GROUP BY actually does to the rows, and why some databases reject SELECT product, rep_id, MAX(amount) ... GROUP BY product while others run it."

What a strong answer should cover:

  • GROUP BY splits the filtered rows into groups with equal grouping keys and returns one row per group; aggregates are computed per group
  • The single-value rule: every SELECT, HAVING and ORDER BY expression must be a grouping key, an aggregate, or functionally dependent on the keys (PostgreSQL allows other columns of a table grouped by its primary key)
  • Engine differences: PostgreSQL and MySQL with ONLY_FULL_GROUP_BY reject bare columns; SQLite accepts them and, with a single MIN or MAX, takes them from that row; ANY_VALUE is the explicit form
  • NULL keys form one group; grouping by an expression; no GROUP BY means one group (one row even on empty input), GROUP BY on empty input returns no rows
  • Where it sits in the logical order (after WHERE, before HAVING), how engines execute it (hash or sort), and when to use a window function instead

Code / implementation expected: Yes β€” grouping by one column, by several columns and an expression, and the bare-column case.

Schema used by the examples:

  • group-by
  • aggregate

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

13 min read Β· 10 sections

Run the code

Edit the query and run it against the tables for this question.

SQLOne grouping key: one output row per product
SQLSeveral keys and an expression: revenue per region per month, with a NULL region group
SQLSQLite only: a bare column next to MAX() comes from the max row (PostgreSQL rejects this)
PostgreSQL: GROUP BY the primary key lets you select the other columns of that table
SELECT r.id, r.name, r.region,
       COUNT(*) AS sales,
       SUM(s.amount) AS revenue,
       ANY_VALUE(s.product) IS NOT NULL AS has_product
FROM reps AS r
JOIN sales AS s ON s.rep_id = r.id
GROUP BY r.id
ORDER BY r.id;

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 24 of 82 in SQL

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All SQL questions
Up nextMedium

What are COMMIT, ROLLBACK, and SAVEPOINT?

Continue