TExcelTAD
Home › PostgreSQL › PostgreSQL Window Functions

PostgreSQL Window Functions

GROUP BY collapses each group into one row. Window functions compute values across a set of related rows without collapsing them: every row stays in the result and gets an extra column, such as its rank, a running total or the previous row's value.

A window function is recognised by its OVER (…) clause:

text
function(...) OVER (
    PARTITION BY …   -- split rows into groups (optional)
    ORDER BY …       -- order inside each group (optional)
    ROWS/RANGE …     -- which neighbouring rows to look at (optional)
)

Aggregates as window functions

Any aggregate becomes a window function when you add OVER. Here each book is shown with its category's average price, keeping every book row:

pgsql · try it yourself
SELECT title, category_id, price,
       round(avg(price) OVER (PARTITION BY category_id), 2) AS category_avg,
       count(*) OVER (PARTITION BY category_id)              AS books_in_category
FROM books
WHERE category_id IN (2, 3)
ORDER BY category_id, price;
       title        | category_id | price | category_avg | books_in_category
--------------------+-------------+-------+--------------+-------------------
 The Last Orbit     |           2 | 16.75 |        18.58 |                 3
 Signal from Kepler |           2 | 18.00 |        18.58 |                 3
 Clockwork Garden   |           2 | 21.00 |        18.58 |                 3
 Murder at Low Tide |           3 | 11.99 |        12.82 |                 3
 The Map Thief      |           3 | 12.99 |        12.82 |                 3
 The Quiet Witness  |           3 | 13.49 |        12.82 |                 3
(6 rows)

OVER () with nothing inside means "the whole result set". It is a quick way to compute percentages of a total:

pgsql · try it yourself
SELECT name, salary,
       round(100 * salary / sum(salary) OVER (), 1) AS pct_of_payroll
FROM employees
ORDER BY salary DESC
LIMIT 4;
     name      | salary  | pct_of_payroll
---------------+---------+----------------
 Rachel Adams  | 9500.00 |           24.3
 Nadia Hussein | 6400.00 |           16.4
 Victor Chen   | 6200.00 |           15.9
 Omar Farouk   | 4800.00 |           12.3
(4 rows)

Ranking: row_number, rank, dense_rank

Function Ties Example values
row_number() always distinct 1, 2, 3, 4
rank() same rank, then a gap 1, 2, 2, 4
dense_rank() same rank, no gap 1, 2, 2, 3

Rank customers by their number of orders. Several customers share the same count, so the three functions differ:

pgsql · try it yourself
SELECT customer_id, count(*) AS orders,
       row_number() OVER (ORDER BY count(*) DESC, customer_id) AS row_no,
       rank()       OVER (ORDER BY count(*) DESC)              AS rank,
       dense_rank() OVER (ORDER BY count(*) DESC)              AS dense_rank
FROM orders
GROUP BY customer_id
ORDER BY orders DESC, customer_id;
 customer_id | orders | row_no | rank | dense_rank
-------------+--------+--------+------+------------
           1 |      3 |      1 |    1 |          1
           2 |      3 |      2 |    1 |          1
           4 |      2 |      3 |    3 |          2
           5 |      2 |      4 |    3 |          2
           9 |      2 |      5 |    3 |          2
          10 |      2 |      6 |    3 |          2
           3 |      1 |      7 |    7 |          3
           6 |      1 |      8 |    7 |          3
           8 |      1 |      9 |    7 |          3
          11 |      1 |     10 |    7 |          3
          12 |      1 |     11 |    7 |          3
          14 |      1 |     12 |    7 |          3
(12 rows)

Customers 1 and 2 share first place. rank then jumps to 3, while dense_rank continues with 2.

Top N per group

Number the rows inside each partition and keep the first ones. Window functions can't be used in WHERE, so wrap the query in a CTE:

pgsql · try it yourself
WITH ranked AS (
    SELECT c.name AS category, b.title, b.price,
           row_number() OVER (PARTITION BY b.category_id ORDER BY b.price DESC) AS pos
    FROM books b JOIN categories c ON c.id = b.category_id
)
SELECT category, title, price
FROM ranked
WHERE pos = 1
ORDER BY price DESC;
    category     |        title         | price
-----------------+----------------------+-------
 Programming     | Postgres in Practice | 44.00
 History         | Empires of Sand      | 27.00
 Science Fiction | Clockwork Garden     | 21.00
 Fiction         | Winter in Sofia      | 17.80
 Mystery         | The Quiet Witness    | 13.49
 Children        | Ten Tiny Dragons     |  8.99
(6 rows)

Running totals

With ORDER BY inside OVER, an aggregate becomes cumulative: it covers all rows from the start of the partition up to the current one. Monthly order counts and a running total for 2024:

pgsql · try it yourself
SELECT to_char(order_date, 'YYYY-MM') AS month,
       count(*) AS orders,
       sum(count(*)) OVER (ORDER BY to_char(order_date, 'YYYY-MM')) AS running_total
FROM orders
GROUP BY month
ORDER BY month;
  month  | orders | running_total
---------+--------+---------------
 2024-01 |      2 |             2
 2024-02 |      2 |             4
 2024-03 |      2 |             6
 2024-04 |      2 |             8
 2024-05 |      1 |             9
 2024-06 |      2 |            11
 2024-07 |      1 |            12
 2024-08 |      2 |            14
 2024-09 |      1 |            15
 2024-10 |      2 |            17
 2024-11 |      1 |            18
 2024-12 |      2 |            20
(12 rows)

The window function runs after GROUP BY, so sum(count(*)) adds up the per-month counts.

Looking at neighbours: lag and lead

lag(x) returns x from the previous row of the window, lead(x) from the next one. Days between consecutive orders of customer 2:

pgsql · try it yourself
SELECT id, order_date,
       lag(order_date) OVER (ORDER BY order_date)              AS previous_order,
       order_date - lag(order_date) OVER (ORDER BY order_date) AS days_since_previous
FROM orders
WHERE customer_id = 2
ORDER BY order_date;
 id | order_date | previous_order | days_since_previous
----+------------+----------------+---------------------
  2 | 2024-01-19 |                |
  8 | 2024-04-27 | 2024-01-19     |                  99
 18 | 2024-11-11 | 2024-04-27     |                 198
(3 rows)

Frames and named windows

The frame clause narrows the window to nearby rows. A moving average of the last 3 orders' values, using a named WINDOW to avoid repeating the definition:

pgsql · try it yourself
WITH totals AS (
    SELECT order_id, sum(quantity * unit_price) AS total
    FROM order_items GROUP BY order_id
)
SELECT order_id, total,
       round(avg(total) OVER w, 2) AS moving_avg_3,
       first_value(total) OVER w   AS first_in_frame
FROM totals
WINDOW w AS (ORDER BY order_id ROWS BETWEEN 2 PRECEDING AND CURRENT ROW)
ORDER BY order_id
LIMIT 6;
 order_id | total | moving_avg_3 | first_in_frame
----------+-------+--------------+----------------
        1 | 54.89 |        54.89 |          54.89
        2 | 36.00 |        45.45 |          54.89
        3 | 43.46 |        44.78 |          54.89
        4 | 15.20 |        31.55 |          36.00
        5 | 44.00 |        34.22 |          43.46
        6 | 39.00 |        32.73 |          15.20
(6 rows)
Function Returns
ntile(n) bucket number 1…n
percent_rank(), cume_dist() relative position 0…1
first_value, last_value, nth_value a value from the frame
lag, lead value from an earlier / later row

Test yourself

How do window functions differ from GROUP BY aggregates?

  1. They are slower
  2. They keep every input row and add a computed column
  3. They can't use aggregates
  4. They only work on dates

Salaries 100, 90, 90, 80. What does rank() give the 80?

  1. 3
  2. 4
  3. 2
  4. 1

Why can't you write WHERE row_number() OVER (...) = 1?

  1. row_number needs arguments
  2. Window functions are evaluated after WHERE; filter in an outer query or CTE
  3. It needs GROUP BY
  4. It works fine