skipnothing/SQL

Window vs GROUP BY

Four rows in orders, two customers, and the same SUM(amount) asked twice: once it answers with two totals, once it answers with four rows that each carry their customer's total along for the ride.

  • ▸Same SUM(amount), same 141.00 and 105.50, yet one phrasing returns two rows and the other returns all four.
  • ▸Show each order's amount beside its customer's total in one query; GROUP BY needs a join to match it.
  • ▸HAVING filters a group in the same query, but WHERE row_number = 1 is rejected: the rank doesn't exist yet.
BUILDS ON
01

Same SUM, Two Row Counts

Here are four orders: two belong to customer 1 (99.00 and 42.00), two to customer 2 (88.00 and 17.50). Ask for each customer's spending with SUM(amount) and a GROUP BY user_id, and four rows go in, two come out: 141.00 and 105.50. The id and amount columns are gone, there was no single id to keep once the rows merged. Now ask the same SUM(amount) with OVER (PARTITION BY user_id) instead. Same two totals, 141.00 and 105.50, but four rows go in and four come out, each order still carrying its own id and amount, with its customer's total written in a new column beside it. One aggregate, one split by customer, two different answers.

On this pair the row count tells them apart: fewer rows out than in means the rows merged. It is not a safe rule. A GROUP BY on a column with one row per group keeps the count, so read the clause. PostgreSQL also reports its plan, the steps it ran (each one a plan node), and that plan names which form ran.

ONE AGGREGATE, TWO OUTPUT SHAPES

Keep going, sign up to unlock the rest

3 more parts in this topic, plus 30+ more topics in SQL.

Sign up, it's freeSee the full SQL