In two sentences
A window function computes something over a group of related rows (a rank, a running total, the previous value)
but, unlike GROUP BY, it keeps every row. You say which rows belong together with PARTITION BY and in what
order with ORDER BY.
See it
| customer_id | order_ts | amount | row_number | running total | previous order |
|---|---|---|---|---|---|
| c1 | 04-01 | 100 | 1 | 100 | NULL |
| c1 | 04-03 | 40 | 2 | 140 | 04-01 |
| c1 | 04-09 | 60 | 3 | 200 | 04-03 |
| c2 | 04-02 | 50 | 1 | 50 | NULL |
| c2 | 04-05 | 20 | 2 | 70 | 04-02 |
Each customer is its own window; the counting restarts at c2. A GROUP BY customer_id would collapse this to two
rows; the window keeps all five and adds columns.
In SQL
SELECT
customer_id, order_ts, amount,
row_number() OVER w AS order_number,
sum(amount) OVER (w ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS running_total,
lag(order_ts) OVER w AS previous_order
FROM orders
WINDOW w AS (PARTITION BY customer_id ORDER BY order_ts);Ties, ranked three ways (sales per product):
| product | sales | row_number | rank | dense_rank |
|---|---|---|---|---|
| A | 90 | 1 | 1 | 1 |
| B | 80 | 2 | 2 | 2 |
| C | 80 | 3 | 2 | 2 |
| D | 70 | 4 | 4 | 3 |
"Top 3 products, with ties" means rank() <= 3 or dense_rank() <= 3 depending on the rule. Ask which.
You can't filter on a window function in the same WHERE; it is computed after WHERE. Wrap it:
SELECT * FROM (
SELECT *, row_number() OVER (PARTITION BY customer_id ORDER BY order_ts DESC) AS rn
FROM orders
) WHERE rn = 1; -- each customer's latest orderCommon mistakes
- Forgetting the frame. With
ORDER BYand no frame,sum() OVERusesRANGE ... CURRENT ROW, which includes every row tied with the current one. Two orders at the same timestamp get the same running total. WriteROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROWwhen you mean "up to this row". row_numberwithout a deterministic order. If two rows tie on theORDER BY, which one gets 1 can change between runs. Add a tie-breaker column.last_valuereturns the current row. Its default frame ends at the current row. UseROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING, orfirst_valuewith the order reversed.- Using
lagon data with missing days. "Previous row" isn't "previous day" if days are missing. See Date spines.
What an interviewer asks next
- "What's the difference between
rankanddense_rank?" Show the tie table. - "How does this run on a billion rows?" Each partition is sorted; a huge single partition (no
PARTITION BY) goes to one worker.
Go further
The PostgreSQL tutorial page is the best five-minute introduction anywhere; everything in it works in Trino.
Practise it
Customer Summary: Recency, Frequency, Monetary, then Top 3 Products per Category, with Ties.