QA Interview Hub · Knowledge base · Quizzes · Українська

SQL › Aggregation

How does GROUP BY work?

GROUP BY splits the rows that passed WHERE into groups by the key value and returns one row per group, with the aggregate computed separately for each. Every column in SELECT must be a grouping key, an aggregate or depend unambiguously on the key. NULLs in the key form one group, and the order of groups is not guaranteed without ORDER BY.

SQL · Aggregates

How many transactions are in each status? And why does the query fail once an email appears in SELECT?

After a release a tester suspects there are more failed transactions. Single rows will not tell: a distribution by status is needed. That is what GROUP BY is for. This lesson explains how the database builds groups, why SELECT is restricted and where grouping silently gives something other than expected.

How it works and why. GROUP BY splits the rows that passed WHERE into groups: rows with the same key value (or set of values) land in one group. Then the aggregate is computed for each group separately and the output is one row per group. For grouping, NULLs count as equal to each other, so all rows with an empty key form one group.

That gives the rule for SELECT: every column must be a grouping key, an aggregate, or depend on the key uniquely. Otherwise the group has many values and the database does not know which to show.

Rows are split into groups

transactions
idstatusamount
1completed50
2failed20
3completed30
4pending10
5failed40
GROUP BY status
statuscntvolume
completed280
failed260
pending110
Figure 1. Five rows became three groups: the aggregate is computed per status separately.

Example: a distribution by status and the email error. The distribution the tester was after:

SELECT status, COUNT(*) AS cnt, SUM(amount) AS volume
FROM transactions
GROUP BY status
ORDER BY status;
-- completed | 2 | 80
-- failed    | 2 | 60
-- pending   | 1 | 10

Now let us add a "convenience": we also want to see a user's email next to the country.

SELECT country, email, COUNT(*)
FROM users
GROUP BY country;
-- PostgreSQL rejects the query:
-- ERROR: column "users.email" must appear in the GROUP BY
--        clause or be used in an aggregate function

A non-grouped column in SELECT

risk

SELECT country, email … GROUP BY country

In PostgreSQL this is an error. In SQLite and in MySQL without ONLY_FULL_GROUP_BY the query runs and shows a random email from the group, and the report looks plausible.

right

SELECT country, COUNT(*) … GROUP BY country

Show only the key and aggregates. If a concrete email is needed, group by the user id or take an aggregate (MIN(email)).

Figure 2. An error from the database is better than a "works" that returns a randomly picked value.

You can group by several columns (every unique combination becomes a group) and by an expression:

-- grouping by an expression: transactions per month (PostgreSQL)
SELECT date_trunc('month', created_at) AS month,
       COUNT(*) AS cnt
FROM transactions
GROUP BY date_trunc('month', created_at)
ORDER BY month;

Limits and alternatives. In PostgreSQL and MySQL GROUP BY accepts an alias from SELECT and a column number (GROUP BY 1), SQL Server forbids the alias, and Oracle accepts it only since 23ai. One more exception to the "column in GROUP BY" rule: if you group by a table's primary key, the other columns of that table depend on it uniquely. PostgreSQL and MySQL 5.7+ recognise this, SQL Server does not, so for portability it is better to list columns explicitly.

-- PostgreSQL: name is allowed because u.id is the primary key
SELECT u.id, u.name, COUNT(o.id) AS orders_cnt
FROM users u
LEFT JOIN orders o ON o.user_id = u.id
GROUP BY u.id;

For intermediate totals (per group and a grand total) there are ROLLUP and GROUPING SETS (PostgreSQL, SQL Server, Oracle; MySQL has WITH ROLLUP). When after grouping you need to keep all source rows and add the group total to each, you need window functions, because GROUP BY collapses them.

Common mistakes.

  • Adding to SELECT a column that is neither in GROUP BY nor in an aggregate: an error, and in softer databases a random value.
  • Grouping too finely (for example together with id): every group is one row and the aggregates collapse nothing.
  • Relying on the order of groups without ORDER BY: the database returns them in arbitrary order and it can change.
  • Missing the group with NULL in the key: it exists and in a report it is a separate row.
  • Grouping after a "one-to-many" JOIN and summing a column from the "one" side: the sums multiply.

Check yourself

The status column has the values completed, failed, NULL and another NULL. How many groups does GROUP BY status return?

Answer

Three: completed, failed and one group for NULL. For grouping, empty values count as equal, so both NULLs together give one result row.

The query SELECT country, email, COUNT(*) FROM users GROUP BY country fails. How do you fix it, depending on what is needed?

Answer

If the count per country is needed, remove email. If a row per user is needed, group by id (or use no GROUP BY at all). If any email from the group will do, take an aggregate such as MIN(email).

Does GROUP BY status guarantee a result ordered by status?

Answer

No. The order of groups is undefined: the database may build them by hashing or by sorting. For a stable order add ORDER BY.

In an interview. Junior: GROUP BY splits rows into groups with equal values and computes an aggregate for each group. Every column in SELECT must be either in GROUP BY or in an aggregate function. I use grouping by status to see the data distribution and spot anomalies, for example an unexpectedly large number of failed. Middle/Senior: The error about a column outside GROUP BY is a safeguard: in softer settings the query returns a random value from the group. NULLs form one group, the order of groups without ORDER BY is not guaranteed, and after a "one-to-many" JOIN the sums multiply. For totals there is ROLLUP and for keeping rows window functions.

More articles in this chapter