DEV Community

Ahmed Awji
Ahmed Awji

Posted on AI-assisted

SQL, GroupBy and Aggregates

How Grouping happens under the hood

Let's take this example:

SELECT
  user_id,
  SUM(amount) as balance
from
  transactions
where
  was_successful = 1
GROUP BY
  user_id
Enter fullscreen mode Exit fullscreen mode

The grouping happens first, and the aggregate calculation happens second.

Here is how the SQL engine processes this conceptually step-by-step:

1. Filter rows (FROM and WHERE)

The engine grabs the transactions table and discards any row where was_successful is not 1 (or true). At this stage, you just have a filtered list of individual transaction rows.

2. Form the buckets (GROUP BY)

Next, the engine organizes the remaining rows into distinct "buckets" based on the grouping key—in this case, user_id. Every row with user_id = 1 goes into bucket 1, rows with user_id = 2 go into bucket 2, and so on:

[Bucket: user_id = 1]
- Row A: amount = 10.50
- Row B: amount = -4.25

[Bucket: user_id = 2]
- Row C: amount = -9.56
- Row D: amount = -50.00
- Row E: amount = 40.00
...
Enter fullscreen mode Exit fullscreen mode

3. Compute the aggregates (SELECT)

Once the buckets exist, the aggregate function (SUM(amount)) runs across each bucket individually:

  • Bucket 1: 10.50 + (-4.25) = 6.25

  • Bucket 2: -9.56 + (-50.00) + 40.00 = -19.56

4. Produce the final output

Each bucket is collapsed into exactly one output row containing the grouping key (user_id) and the computed result (balance).

This order of operations is also why you cannot use an aggregate function like SUM() directly in a WHERE clause—the WHERE clause filters rows before any groups or buckets are formed.

Order of Operations:
This is the order which SQL executes the parts of a query:

  1. FROM: Pick the table.

  2. WHERE: Filter individual rows.

  3. GROUP BY: Group the remaining rows into buckets.

  4. HAVING: Filter the grouped buckets.

  5. SELECT: Calculate expressions and aggregates (like SUM()).

Because WHERE runs at step 2, the database is examining rows one by one. At that moment, no groups exist yet, and no sums have been calculated.

If you try to write something like this:

SELECT user_id, SUM(amount)
FROM transactions
WHERE SUM(amount) > 0  -- ERROR!
GROUP BY user_id;
Enter fullscreen mode Exit fullscreen mode

The database will throw an error: misuse of aggregate function SUM(). It cannot check whether SUM(amount) > 0 during the WHERE step because it hasn't grouped the rows or summed them yet.

How to filter on aggregated results

If you want to filter based on an aggregate, SQL provides the HAVING clause, which runs after grouping and aggregating (step 4):

SELECT user_id, SUM(amount) AS balance
FROM transactions
WHERE was_successful = 1   -- Filters individual rows FIRST
GROUP BY user_id          -- Groups rows into buckets SECOND
HAVING SUM(amount) > 0;   -- Filters the grouped buckets THIRD
Enter fullscreen mode Exit fullscreen mode

In short:

  • WHERE filters rows before aggregation.

  • HAVING filters groups after aggregation.

Top comments (0)