skipnothing/SQL

PARTITION BY & ORDER BY

Four orders sit in orders, two from user 1 and two from user 2, and adding every amount gives one number: 246.50. Ask instead for each user's total beside their rows and that 246.50 splits into 141.00 and 105.50.

  • ▸Split four orders into two users and the one total 246.50 becomes 141.00 and 105.50, all four rows still standing.
  • ▸The same SUM flips from a flat group total to a climbing per-row value once an ordering joins the parentheses.
  • ▸Ranking and the climbing total both reset to the start at every boundary between one user and the next.
BUILDS ON
01

One window per group

Last topic handed every row the same whole-table total: an empty OVER () meant each order's window was the entire result. On these four orders that total is 246.50, written on all four. These orders, though, belong to two users, and the useful question is each user's own total, not everyone's combined.

Name the column to split on inside the parentheses:

SELECT id, user_id, amount,
       SUM(amount) OVER (PARTITION BY user_id) AS user_total
FROM orders;
-- id   user_id  amount   user_total
-- 101  1        99.00    141.00
-- 102  1        42.00    141.00
-- 103  2        88.00    105.50
-- 104  2        17.50    105.50

PARTITION BY user_id carves the rows into groups that share a user_id, and the SUM runs once inside each group instead of once across the whole table. User 1's two orders both read 141.00; user 2's both read 105.50. The window shrank from every row down to the rows in one user's own group. Nothing collapsed: four rows went in and four came out, each still carrying its amount beside its group's total.

One more key to try: date_trunc('month', created_at) rounds each date down to the first of its month, so orders 101 and 102 both read 2026-01-01 and splitting on it groups orders by month.

THE WINDOW SHRINKS TO ONE GROUP

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