shuffleet
Home
Practice
Problems
Lessons
Plans
Compete
Challenges
Interviews
Leaderboard
Progress
Skills
Analytics
Submissions
Account
Settings

Window functions

Junior · 3 min read

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_idorder_tsamountrow_numberrunning totalprevious order
c104-011001100NULL
c104-0340214004-01
c104-0960320004-03
c204-0250150NULL
c204-052027004-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.

Each customer is its own window: every row is kept, the running total adds up the frame, and it restarts for the next customer

In SQL

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):

productsalesrow_numberrankdense_rank
A90111
B80222
C80322
D70443

"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:

SQL
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 order

Common mistakes

  • Forgetting the frame. With ORDER BY and no frame, sum() OVER uses RANGE ... CURRENT ROW, which includes every row tied with the current one. Two orders at the same timestamp get the same running total. Write ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW when you mean "up to this row".
  • row_number without a deterministic order. If two rows tie on the ORDER BY, which one gets 1 can change between runs. Add a tie-breaker column.
  • last_value returns the current row. Its default frame ends at the current row. Use ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING, or first_value with the order reversed.
  • Using lag on 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 rank and dense_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.