Postgres window functions in practice: top-N per group, running totals, streaks, and the frame that trips everyone up

A hands-on guide to PostgreSQL window functions: ROW_NUMBER vs RANK vs DENSE_RANK, top-N per group, running totals and moving averages, LAG and LEAD, gaps and islands, sessionization, and deduplication. Explains the default window frame behind most wrong answers, the last_value trap, and when a LATERAL join beats a window function by more than 100x. Every query tested on Postgres 17.11.

Ripley15 min read
On this page

Window functions are the part of SQL that turns "export it to a spreadsheet" into one query: rank rows inside each group, compute a running total, compare a row with the one before it, find login streaks, split clicks into sessions. They are also where correct-looking queries return wrong numbers, almost always because of one default nobody reads: the window frame. This post works through the eight patterns we reach for most, on a small table you can paste into psql, with the real output from PostgreSQL 17.11, the major version Relyt One runs. Along the way we show the three traps (ties in row_number(), the default frame, and last_value()), and finish with a benchmark on 2 million rows where the window-function version of "latest order per customer" takes about a second and a LATERAL join takes 3 to 7 milliseconds. If you only need the definition, our glossary entry has it in one screen.

The short version

You wantUseWatch out for
A group total next to every rowsum(x) OVER (PARTITION BY g)Nothing, this one is easy
Top N per grouprow_number() OVER (PARTITION BY g ORDER BY x DESC, id) in a subquery, then WHERE rn <= NTies: add a unique tiebreaker, or use rank() to keep them
Running totalsum(x) OVER (ORDER BY t, id ROWS UNBOUNDED PRECEDING)Without ROWS and a unique order, rows with the same t get the same total
Moving averageavg(x) OVER (ORDER BY day ROWS 2 PRECEDING) or RANGE '2 days' PRECEDINGROWS counts rows, RANGE counts days; they differ when days are missing
Previous / next rowlag(x) / lead(x)The previous row is not the previous day
Last value in a groupfirst_value(x) with the order reversedlast_value(x) with the default frame returns the current row (or its last tie)
Streaks of consecutive daysday - row_number() as a group keyDuplicate days break it; deduplicate first
Latest row per group on a big tableLATERAL (... ORDER BY t DESC LIMIT 1) with an indexA window function reads every row, index or not

The data

Everything below runs on a throwaway Postgres in Docker:

docker run -d --name wf -e POSTGRES_PASSWORD=x postgres:17.11-alpine
until docker exec wf pg_isready -U postgres -q; do sleep 1; done
docker exec -it wf psql -U postgres

Eight orders across two regions. Two days have two orders each, and there are no orders on November 4. Both details matter later.

CREATE TABLE orders (
  id         int GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  customer   text NOT NULL,
  region     text NOT NULL,
  ordered_on date NOT NULL,
  amount     numeric(10,2) NOT NULL
);
INSERT INTO orders (customer, region, ordered_on, amount) VALUES
  ('ada',   'eu', '2026-11-01', 120.00),
  ('linus', 'eu', '2026-11-01',  80.00),
  ('grace', 'us', '2026-11-02', 200.00),
  ('ada',   'eu', '2026-11-03',  50.00),
  ('ken',   'us', '2026-11-03', 200.00),
  ('barbara','us','2026-11-06',  90.00),
  ('linus', 'eu', '2026-11-05', 300.00),
  ('grace', 'us', '2026-11-05',  40.00);

GROUP BY collapses rows, a window keeps them

GROUP BY region gives you two rows, one per region. Put the same sum behind OVER (PARTITION BY region) and you keep all eight rows, each with its region's total next to it. That's what makes "what share of its region is this order" a one-liner:

SELECT id, customer, region, amount,
       sum(amount) OVER (PARTITION BY region) AS region_total,
       round(100 * amount / sum(amount) OVER (PARTITION BY region), 1) AS pct_of_region
FROM orders ORDER BY region, id;
 id | customer | region | amount | region_total | pct_of_region
----+----------+--------+--------+--------------+---------------
  1 | ada      | eu     | 120.00 |       550.00 |          21.8
  2 | linus    | eu     |  80.00 |       550.00 |          14.5
  4 | ada      | eu     |  50.00 |       550.00 |           9.1
  7 | linus    | eu     | 300.00 |       550.00 |          54.5
  3 | grace    | us     | 200.00 |       530.00 |          37.7
  5 | ken      | us     | 200.00 |       530.00 |          37.7
  6 | barbara  | us     |  90.00 |       530.00 |          17.0
  8 | grace    | us     |  40.00 |       530.00 |           7.5

Everything inside OVER (...) answers three questions for the current row:

  1. PARTITION BY: which rows are in my group? Leave it out and the whole result is one group.
  2. ORDER BY: in what order are the rows of my group? Ranking functions and lag / lead need it to mean anything.
  3. The frame (ROWS, RANGE or GROUPS ...): which rows of my group does an aggregate like sum actually look at? If you don't write one, Postgres picks a default, and that default is where most of the surprises in this post come from.

The first six orders as one partition ordered by date, with the current row highlighted and three frames drawn next to it: the default RANGE frame reaches the current row's last peer, the ROWS frame stops at the current row, and no ORDER BY means the whole partition.

One more rule before the patterns: window functions run after WHERE, GROUP BY and HAVING, so they can only appear in the SELECT list and in ORDER BY. You can't filter on them directly; you'll see the fix in the next section.

1. Top N per group, and the tie problem

Postgres has three functions that number rows in order. They agree until two rows tie:

SELECT region, customer, amount,
       row_number() OVER w AS row_number,
       rank()       OVER w AS rank,
       dense_rank() OVER w AS dense_rank
FROM orders
WINDOW w AS (PARTITION BY region ORDER BY amount DESC)
ORDER BY region, amount DESC, customer;
 region | customer | amount | row_number | rank | dense_rank
--------+----------+--------+------------+------+------------
 eu     | linus    | 300.00 |          1 |    1 |          1
 eu     | ada      | 120.00 |          2 |    2 |          2
 eu     | linus    |  80.00 |          3 |    3 |          3
 eu     | ada      |  50.00 |          4 |    4 |          4
 us     | grace    | 200.00 |          2 |    1 |          1
 us     | ken      | 200.00 |          1 |    1 |          1
 us     | barbara  |  90.00 |          3 |    3 |          2
 us     | grace    |  40.00 |          4 |    4 |          3

(WINDOW w AS (...) names a window once so several functions can share it.)

Look at the two 200.00 orders in us. rank() gives both 1 and skips to 3. dense_rank() gives both 1 and continues with 2. row_number() must pick one of them to be 1, and here it picked ken, even though grace's order came first. Nothing in ORDER BY amount DESC tells it how to break the tie, so the order among tied rows is whatever the sort happened to produce. It can change after an UPDATE, a VACUUM FULL or a different plan. If your "top seller" report flips between two people from one day to the next with no new data, this is why.

So for top N per group, decide what a tie means and say it in SQL:

  • Exactly N rows per group: row_number() with a unique column at the end of ORDER BY.
  • Everyone who ties for the last place too: rank() and WHERE rnk <= N.

Since you can't put a window function in WHERE (Postgres answers ERROR: window functions are not allowed in WHERE), compute it in a subquery and filter outside:

SELECT region, customer, amount
FROM (
  SELECT region, customer, amount,
         row_number() OVER (PARTITION BY region ORDER BY amount DESC, id) AS rn
  FROM orders
) ranked
WHERE rn <= 2
ORDER BY region, rn;
 region | customer | amount
--------+----------+--------
 eu     | linus    | 300.00
 eu     | ada      | 120.00
 us     | grace    | 200.00
 us     | ken      | 200.00

Some databases have a QUALIFY clause for this. Postgres doesn't; in Postgres 17 ... FROM orders QUALIFY rn = 1 is a syntax error. For exactly one row per group, Postgres's own DISTINCT ON is shorter:

SELECT DISTINCT ON (region) region, customer, amount
FROM orders ORDER BY region, amount DESC, id;

2. Running totals, and the default frame

A running total looks like the easiest window there is:

SELECT ordered_on, customer, amount,
       sum(amount) OVER (ORDER BY ordered_on) AS running_total
FROM orders ORDER BY ordered_on, id;
 ordered_on | customer | amount | running_total
------------+----------+--------+---------------
 2026-11-01 | ada      | 120.00 |        200.00
 2026-11-01 | linus    |  80.00 |        200.00
 2026-11-02 | grace    | 200.00 |        400.00
 2026-11-03 | ada      |  50.00 |        650.00
 2026-11-03 | ken      | 200.00 |        650.00
 2026-11-05 | linus    | 300.00 |        990.00
 2026-11-05 | grace    |  40.00 |        990.00
 2026-11-06 | barbara  |  90.00 |       1080.00

The first row says the running total after ada's 120.00 order is 200.00. That isn't a bug in sum. When you write ORDER BY without a frame, the default frame is RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW, and in RANGE mode "current row" means the current row and all its peers: every row with the same ORDER BY value. Both November 1 orders are peers, so both see the sum of both.

Sometimes that's what you want: a running total per day, repeated on each order of that day. When you want one step per row, say so with ROWS, and make the order unique so the steps come out in the same order every time:

SELECT ordered_on, customer, amount,
       sum(amount) OVER (ORDER BY ordered_on, id
                         ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS running_total
FROM orders ORDER BY ordered_on, id;
 ordered_on | customer | amount | running_total
------------+----------+--------+---------------
 2026-11-01 | ada      | 120.00 |        120.00
 2026-11-01 | linus    |  80.00 |        200.00
 2026-11-02 | grace    | 200.00 |        400.00
 2026-11-03 | ada      |  50.00 |        450.00
 2026-11-03 | ken      | 200.00 |        650.00
 2026-11-05 | linus    | 300.00 |        950.00
 2026-11-05 | grace    |  40.00 |        990.00
 2026-11-06 | barbara  |  90.00 |       1080.00

The same default explains a second surprise: sum(amount) OVER (), with no ORDER BY at all, gives the grand total on every row, because without an order every row is a peer of every other row.

Moving averages: ROWS counts rows, RANGE counts values

For a 3-day moving average, aggregate to one row per day first, then window over the days. Here the difference between ROWS and RANGE is not about ties but about gaps: there were no orders on November 4.

WITH daily AS (
  SELECT ordered_on, sum(amount) AS revenue
  FROM orders GROUP BY ordered_on
)
SELECT ordered_on, revenue,
       round(avg(revenue) OVER (ORDER BY ordered_on
             ROWS BETWEEN 2 PRECEDING AND CURRENT ROW), 2) AS avg_3_rows,
       round(avg(revenue) OVER (ORDER BY ordered_on
             RANGE BETWEEN '2 days' PRECEDING AND CURRENT ROW), 2) AS avg_3_days
FROM daily ORDER BY ordered_on;
 ordered_on | revenue | avg_3_rows | avg_3_days
------------+---------+------------+------------
 2026-11-01 |  200.00 |     200.00 |     200.00
 2026-11-02 |  200.00 |     200.00 |     200.00
 2026-11-03 |  250.00 |     216.67 |     216.67
 2026-11-05 |  340.00 |     263.33 |     295.00
 2026-11-06 |   90.00 |     226.67 |     215.00

On November 5 the ROWS version averages the last three rows that exist (November 2, 3 and 5), spanning four calendar days. The RANGE '2 days' version averages the days from November 3 to 5 that have rows. Neither treats the missing day as zero; if you want that, generate the full calendar with generate_series and LEFT JOIN the revenue onto it before the window. RANGE with an offset needs exactly one ORDER BY column of a type you can subtract from, such as a number, a date or a timestamp.

There's a third mode, GROUPS, that counts peer groups instead of rows: GROUPS BETWEEN 1 PRECEDING AND CURRENT ROW means "this date's orders plus the orders of the previous date that has any", however many there are. Together with EXCLUDE CURRENT ROW (for example, "the average of the other orders in my region"), it has been there since Postgres 11.

3. The last_value() trap

You want each order next to the biggest and the smallest order of its region. first_value works, last_value doesn't:

SELECT region, customer, amount,
       first_value(customer) OVER w AS biggest,
       last_value(customer)  OVER w AS smallest_wrong,
       last_value(customer)  OVER (w ROWS BETWEEN UNBOUNDED PRECEDING
                                       AND UNBOUNDED FOLLOWING) AS smallest
FROM orders
WINDOW w AS (PARTITION BY region ORDER BY amount DESC, id)
ORDER BY region, amount DESC, id;
 region | customer | amount | biggest | smallest_wrong | smallest
--------+----------+--------+---------+----------------+----------
 eu     | linus    | 300.00 | linus   | linus          | ada
 eu     | ada      | 120.00 | linus   | ada            | ada
 eu     | linus    |  80.00 | linus   | linus          | ada
 eu     | ada      |  50.00 | linus   | ada            | ada
 us     | grace    | 200.00 | grace   | grace          | grace
 us     | ken      | 200.00 | grace   | ken            | grace
 us     | barbara  |  90.00 | grace   | barbara        | grace
 us     | grace    |  40.00 | grace   | grace          | grace

smallest_wrong is just the current row's customer. It's the same default frame again: it ends at the current row, so the last value in the frame is the current row. The Postgres manual itself warns that this "is likely to give unhelpful results for last_value". Either widen the frame to the whole partition, as in the smallest column, or flip the sort and use first_value, which only needs the start of the frame and is harder to get wrong.

4. Comparing with the previous row: lag and lead

lag(x) is the value of x one row back in the window's order; lead(x) is one row ahead. Day-over-day change:

WITH daily AS (
  SELECT ordered_on, sum(amount) AS revenue FROM orders GROUP BY ordered_on
)
SELECT ordered_on, revenue,
       lag(revenue) OVER (ORDER BY ordered_on) AS prev_day,
       revenue - lag(revenue) OVER (ORDER BY ordered_on) AS change,
       round(100.0 * (revenue / lag(revenue) OVER (ORDER BY ordered_on) - 1), 1) AS pct_change
FROM daily ORDER BY ordered_on;
 ordered_on | revenue | prev_day | change  | pct_change
------------+---------+----------+---------+------------
 2026-11-01 |  200.00 |          |         |
 2026-11-02 |  200.00 |   200.00 |    0.00 |        0.0
 2026-11-03 |  250.00 |   200.00 |   50.00 |       25.0
 2026-11-05 |  340.00 |   250.00 |   90.00 |       36.0
 2026-11-06 |   90.00 |   340.00 | -250.00 |      -73.5

Two things to notice. The first row has no previous row, so lag returns NULL (pass a third argument, as in lag(revenue, 1, 0), to get a default instead). And the "previous day" of November 5 is November 3: lag means previous row, not previous day. If gaps matter, fill the calendar first, as with the moving average.

With PARTITION BY, the same idea gives per-customer metrics, such as days since the customer's previous order:

SELECT customer, ordered_on, amount,
       ordered_on - lag(ordered_on) OVER (PARTITION BY customer ORDER BY ordered_on)
         AS days_since_last
FROM orders ORDER BY customer, ordered_on;

5. Streaks: gaps and islands

"How many days in a row did each user log in?" is the classic gaps-and-islands problem. Here are two users' login days:

CREATE TABLE logins (user_name text NOT NULL, day date NOT NULL,
                     PRIMARY KEY (user_name, day));
INSERT INTO logins VALUES
  ('ada', '2026-11-01'), ('ada', '2026-11-02'), ('ada', '2026-11-03'),
  ('ada', '2026-11-05'), ('ada', '2026-11-06'),
  ('ken', '2026-11-02'), ('ken', '2026-11-04'), ('ken', '2026-11-05'),
  ('ken', '2026-11-06'), ('ken', '2026-11-07');

The trick: number each user's days 1, 2, 3, … and subtract that number from the date. Inside a run of consecutive days, the date and the number both go up by one, so the difference stays the same. After a gap, the date jumps more than the number, and the difference changes.

 user_name |    day     | rn |    grp
-----------+------------+----+------------
 ada       | 2026-11-01 |  1 | 2026-10-31
 ada       | 2026-11-02 |  2 | 2026-10-31
 ada       | 2026-11-03 |  3 | 2026-10-31
 ada       | 2026-11-05 |  4 | 2026-11-01
 ada       | 2026-11-06 |  5 | 2026-11-01

grp has no meaning of its own; it's just a key that's equal within an island. Group by it:

SELECT user_name,
       min(day) AS streak_start,
       max(day) AS streak_end,
       count(*) AS days
FROM (
  SELECT user_name, day,
         day - row_number() OVER (PARTITION BY user_name ORDER BY day)::int AS grp
  FROM logins
) t
GROUP BY user_name, grp
ORDER BY user_name, streak_start;
 user_name | streak_start | streak_end | days
-----------+--------------+------------+------
 ada       | 2026-11-01   | 2026-11-03 |    3
 ada       | 2026-11-05   | 2026-11-06 |    2
 ken       | 2026-11-02   | 2026-11-02 |    1
 ken       | 2026-11-04   | 2026-11-07 |    4

The ::int cast is needed because row_number() returns bigint, and the only integer type you can subtract from a date is integer. The trick assumes one row per user per day; the primary key guarantees it here. On a raw events table, take SELECT DISTINCT user_name, (at AT TIME ZONE 'UTC')::date first (or your users' time zone), or two logins on the same day will split the streak.

6. Sessions: a new session after 30 minutes of silence

Web analytics defines a session as a run of activity with no gap longer than some timeout. That's two window functions: lag to flag the rows that start a session, then a running sum of those flags to number the sessions.

CREATE TABLE clicks (user_name text NOT NULL, at timestamptz NOT NULL);
INSERT INTO clicks VALUES
  ('ada', '2026-11-09 09:00:00+00'), ('ada', '2026-11-09 09:05:00+00'),
  ('ada', '2026-11-09 09:20:00+00'), ('ada', '2026-11-09 11:00:00+00'),
  ('ada', '2026-11-09 11:10:00+00'), ('ken', '2026-11-09 10:00:00+00'),
  ('ken', '2026-11-09 10:45:00+00');

WITH flagged AS (
  SELECT user_name, at,
         CASE WHEN at - lag(at) OVER (PARTITION BY user_name ORDER BY at)
                   <= interval '30 minutes'
              THEN 0 ELSE 1 END AS is_new_session
  FROM clicks
),
numbered AS (
  SELECT user_name, at,
         sum(is_new_session) OVER (PARTITION BY user_name ORDER BY at) AS session_no
  FROM flagged
)
SELECT user_name, session_no,
       min(at) AS started, max(at) AS ended, count(*) AS clicks
FROM numbered
GROUP BY user_name, session_no
ORDER BY user_name, session_no;
 user_name | session_no |        started         |         ended          | clicks
-----------+------------+------------------------+------------------------+--------
 ada       |          1 | 2026-11-09 09:00:00+00 | 2026-11-09 09:20:00+00 |      3
 ada       |          2 | 2026-11-09 11:00:00+00 | 2026-11-09 11:10:00+00 |      2
 ken       |          1 | 2026-11-09 10:00:00+00 | 2026-11-09 10:00:00+00 |      1
 ken       |          2 | 2026-11-09 10:45:00+00 | 2026-11-09 10:45:00+00 |      1

A user's first click has no previous click, so lag is NULL, the comparison is NULL, and the CASE falls through to 1: a new session, which is right. The running sum uses the default frame, so if a user has two clicks with the exact same timestamp they share a session number, which is also what you want here. You can't nest one window function inside another (Postgres rejects it with window function calls cannot be nested); that's why the flags go in their own CTE.

7. Deduplicate, keeping the newest row

Same idea as top N, with DELETE. Keep the newest signup per email:

CREATE TABLE signups (id int GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
                      email text NOT NULL, created_at timestamptz NOT NULL);
INSERT INTO signups (email, created_at) VALUES
  ('ada@example.com', '2026-11-01 10:00+00'),
  ('ada@example.com', '2026-11-03 10:00+00'),
  ('ken@example.com', '2026-11-02 10:00+00'),
  ('ada@example.com', '2026-11-02 10:00+00');

BEGIN;
DELETE FROM signups
WHERE id IN (
  SELECT id FROM (
    SELECT id,
           row_number() OVER (PARTITION BY email
                              ORDER BY created_at DESC, id DESC) AS rn
    FROM signups
  ) d
  WHERE rn > 1
);
-- DELETE 2: only ada's 2026-11-03 signup and ken's are left
COMMIT;  -- or ROLLBACK if the count isn't what you expected

The id DESC tiebreaker matters for the same reason as in section 1: if two duplicates share a created_at, you want to know which one survives. Check the row count before you commit, then add a unique constraint so you don't have to run it again.

8. Conditional windows with FILTER

Aggregate window functions accept FILTER, which is often cleaner than a CASE inside the sum:

SELECT ordered_on, region, amount,
       count(*)    FILTER (WHERE amount >= 100)  OVER w AS big_orders_so_far,
       sum(amount) FILTER (WHERE region = 'eu')  OVER w AS eu_running
FROM orders
WINDOW w AS (ORDER BY ordered_on, id)
ORDER BY ordered_on, id;

Only aggregates take FILTER; row_number() FILTER (...) is an error. And since window functions run after GROUP BY, you can rank the groups themselves: SELECT region, sum(amount), rank() OVER (ORDER BY sum(amount) DESC) FROM orders GROUP BY region ranks the regions by revenue.

When not to use a window function

Window functions are convenient, but they have to read every row that feeds them; they can't skip the rest of a partition once they have what they need. On a big table, "the latest order per customer" is where that shows. We loaded 2,000,000 orders for 1,000 customers into the same postgres:17.11-alpine container (Apple M1 Pro, 5 CPUs for Docker, default settings including work_mem = 4MB) and ran each version three times:

QueryPlanExecution time
Window, no indexSort 2,000,000 rows, spilling 80 MB to disk924–930 ms
Window, work_mem = 256MBSort in memory (about 140 MB)816–881 ms
Window, index on (customer_id, ordered_at DESC)Index scan over all 2,000,000 rows, no sort1,024–1,087 ms
LATERAL ... LIMIT 1, same index1,000 index lookups, one row each3.0–6.7 ms

The window query was:

SELECT customer_id, id, ordered_at, amount
FROM (
  SELECT customer_id, id, ordered_at, amount,
         row_number() OVER (PARTITION BY customer_id ORDER BY ordered_at DESC) AS rn
  FROM big_orders
) t
WHERE rn = 1;

Postgres 15 added an optimization for exactly this shape: EXPLAIN shows Run Condition: (row_number() OVER (?) <= 1), which lets the window stop emitting rows for a customer once it's past row 1. But it still has to read and sort every order to find where each customer starts. The index removes the sort, and in our runs the planner chose it, yet the query got slightly slower, most likely because reading 2 million rows in index order costs more than reading them sequentially and sorting.

The fast version asks a different question: for each customer, jump into the index and take one row.

CREATE INDEX ON big_orders (customer_id, ordered_at DESC);

SELECT c.id AS customer_id, o.id, o.ordered_at, o.amount
FROM customers c
CROSS JOIN LATERAL (
  SELECT id, ordered_at, amount
  FROM big_orders
  WHERE customer_id = c.id
  ORDER BY ordered_at DESC
  LIMIT 1
) o;

That's 1,000 index lookups instead of 2,000,000 rows. It needs a table listing the groups (a SELECT DISTINCT over the big table would read every row again), and it pays off when each group has many rows; with millions of customers and two orders each, the window function is the better plan. The rule of thumb we use: window functions for analytics over the rows you've already filtered, LATERAL ... LIMIT for "latest N per thing" on hot paths.

Try it on a branch

Every query here is plain Postgres; nothing needs an extension. If you're on Relyt One, the fastest way to try them against your real data is a branch: it starts from the parent's data with copy-on-write storage, runs on its own compute, and you can throw it away when you're done, so a heavy analytical query or a deduplicating DELETE never touches production. You can even start the branch from a moment in the past (within the project's history retention, up to 3 hours) to compare the numbers from before a bad import with today's.

For the short definition and the basic syntax, see the window functions entry in our Postgres glossary. The Postgres manual covers the full frame syntax in Window Function Calls and the function list in Window Functions.

Start for free

TagsPostgressqlwindow-functionsperformance

Written by

Ripley

Follow the blog with RSS

Add the feed to your RSS reader and new articles show up there as soon as they are published.

Subscribe via RSS

Your next database is one branch away.

Create a free project in under a minute. No credit card, no setup.

Back to blog