Sub topic 9
Filtered aggregates as window functions
This chapter assumes you know how GROUP BY aggregates work, you have met FILTER (WHERE ...) on grouped aggregates, and you have seen basic window syntax (OVER, PARTITION BY, ORDER BY). It uses the orders table from earlier chapters.
What changes in a window context
A grouped aggregate collapses rows. A window aggregate keeps every row and attaches a computed value to it. You can add FILTER to a window aggregate. It controls which rows in the window frame feed the aggregate, and it does not remove any rows from the output.
The syntax puts FILTER between the aggregate call and OVER:
aggregate_function(args) FILTER (WHERE condition) OVER (window_definition)Three points follow from this:
- Every input row still appears in the result.
- The condition is tested for each row in the current row's frame. Rows that fail it are skipped by the aggregate.
- The current row can fail the condition and still receive a value, because its frame may contain rows that pass.
Sample data
The examples below use a small data set so you can check the numbers by hand.
CREATE TABLE orders (
id bigint PRIMARY KEY,
customer_id bigint NOT NULL,
status text NOT NULL,
amount numeric(10,2) NOT NULL,
created_at timestamptz NOT NULL
);
INSERT INTO orders (id, customer_id, status, amount, created_at) VALUES
(1, 1, 'paid', 20.00, '2026-01-05 10:00+00'),
(2, 1, 'pending', 15.00, '2026-01-12 10:00+00'),
(3, 1, 'paid', 30.00, '2026-02-03 10:00+00'),
(4, 1, 'refunded', 30.00, '2026-02-10 10:00+00'),
(5, 1, 'paid', 25.00, '2026-03-01 10:00+00'),
(6, 2, 'refunded', 50.00, '2026-01-20 10:00+00'),
(7, 2, 'paid', 40.00, '2026-02-15 10:00+00');A running total over paid orders only
A running total sums the rows from the start of the partition up to the current row. With FILTER, only paid rows contribute.
SELECT
id,
customer_id,
status,
amount,
sum(amount) FILTER (WHERE status = 'paid')
OVER (PARTITION BY customer_id ORDER BY created_at) AS running_paid_total
FROM orders
ORDER BY customer_id, created_at;| id | customer_id | status | amount | running_paid_total |
|---|---|---|---|---|
| 1 | 1 | paid | 20.00 | 20.00 |
| 2 | 1 | pending | 15.00 | 20.00 |
| 3 | 1 | paid | 30.00 | 50.00 |
| 4 | 1 | refunded | 30.00 | 50.00 |
| 5 | 1 | paid | 25.00 | 75.00 |
| 6 | 2 | refunded | 50.00 | NULL |
| 7 | 2 | paid | 40.00 | 40.00 |
Rows 2 and 4 are not paid, yet they show a running total. Their frames include earlier paid rows, so the total carries forward. Row 6 is the first row for customer 2, and its frame holds no paid rows, so sum returns NULL.
The empty-set rule from the NULL chapter applies to every frame. sum over zero qualifying rows is NULL. count over zero qualifying rows is 0. Wrap sum in coalesce when the report needs a number:
SELECT
id,
customer_id,
coalesce(
sum(amount) FILTER (WHERE status = 'paid')
OVER (PARTITION BY customer_id ORDER BY created_at),
0
) AS running_paid_total
FROM orders
ORDER BY customer_id, created_at;The coalesce goes outside the whole window expression, including OVER.
Why not use WHERE?
Putting WHERE status = 'paid' on the query would remove the pending and refunded rows from the output, and from the window too. That is the right choice when you only want paid rows in the report. FILTER is the right choice when you want every row listed and the aggregate to look at a subset.
The reason lies in the logical order of evaluation. WHERE runs before window functions and decides which rows exist. FILTER runs inside each window aggregate and only affects that one expression.
This also means you can use several window aggregates with different filters in the same SELECT, each seeing the same set of rows but counting different subsets.
Frames, peers and ties
When a window has ORDER BY and no explicit frame, PostgreSQL uses RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW. In RANGE mode, rows with the same ORDER BY value (peers) are all included in each other's frames. If two paid orders for one customer have the same created_at, both show the same running total, which includes both amounts.
Two ways to avoid that:
- Add a tie-breaker to the window ordering, such as
ORDER BY created_at, id. - Use
ROWSmode explicitly.
Both leave FILTER unchanged. FILTER only decides which rows in the frame count.
Moving windows: refunds in the last three orders
An explicit ROWS frame gives a sliding window. This query counts refunded orders among each customer's current and two previous orders:
SELECT
id,
customer_id,
status,
count(*) FILTER (WHERE status = 'refunded')
OVER (
PARTITION BY customer_id
ORDER BY created_at
ROWS BETWEEN 2 PRECEDING AND CURRENT ROW
) AS refunds_in_last_3
FROM orders
ORDER BY customer_id, created_at;| id | customer_id | refunds_in_last_3 |
|---|---|---|
| 1 | 1 | 0 |
| 2 | 1 | 0 |
| 3 | 1 | 0 |
| 4 | 1 | 1 |
| 5 | 1 | 1 |
| 6 | 2 | 1 |
| 7 | 2 | 1 |
For order 5, the frame holds orders 3, 4 and 5, and order 4 is the refund. Because the aggregate is count, empty frames give 0 and no coalesce is needed.
Ratios and named windows
Two window aggregates over the same partition can be divided to give a per-row share. When the same window is used more than once, a WINDOW clause avoids repeating it:
SELECT
id,
customer_id,
round(
100.0 * count(*) FILTER (WHERE status = 'paid') OVER w
/ count(*) OVER w,
1
) AS customer_paid_pct
FROM orders
WINDOW w AS (PARTITION BY customer_id)
ORDER BY customer_id, id;With no ORDER BY in the window, the frame is the entire partition, so every row of a customer shows the same percentage. For the sample data, customer 1 has 3 paid orders out of 5 and shows 60.0. Customer 2 has 1 out of 2 and shows 50.0.
The denominator count(*) OVER w is at least 1 for any row, because the row itself is in its own partition. There is no division by zero.
FILTER is written on the aggregate call, before OVER w. The named window does not contain the filter.
Window aggregates over grouped results
You can combine a grouped aggregate with a window aggregate in one query. The window runs after grouping, so it sees one row per group. A filtered grouped aggregate can sit inside a window aggregate:
SELECT
date_trunc('month', created_at) AS month,
sum(amount) FILTER (WHERE status = 'paid') AS paid_revenue,
sum(sum(amount) FILTER (WHERE status = 'paid'))
OVER (ORDER BY date_trunc('month', created_at)) AS running_paid_revenue
FROM orders
GROUP BY 1
ORDER BY 1;With the session time zone set to UTC, the result for the sample data is:
| month | paid_revenue | running_paid_revenue |
|---|---|---|
| 2026-01-01 | 20.00 | 20.00 |
| 2026-02-01 | 70.00 | 90.00 |
| 2026-03-01 | 25.00 | 115.00 |
Read the nested call from the inside out. The inner sum(...) FILTER (...) produces one value per month. The outer sum(...) OVER (...) adds those monthly values cumulatively. The outer window has no FILTER because the filtering already happened per month.
date_trunc on a timestamptz uses the session time zone, so month boundaries move if the zone changes. Set the zone deliberately in reports.
If a month had no paid orders, the inner sum would be NULL. The outer running sum skips NULL inputs, so it would carry the previous total forward. If the first month were NULL, the running total would also be NULL, so coalesce applies here too.
What FILTER cannot do in a window
FILTER works only on aggregate functions. Functions that exist only as window functions reject it:
SELECT
id,
row_number() FILTER (WHERE status = 'paid')
OVER (PARTITION BY customer_id ORDER BY created_at)
FROM orders;PostgreSQL stops with an error stating that FILTER is not implemented for non-aggregate window functions. This applies to row_number, rank, dense_rank, lag, lead, first_value, ntile and similar functions.
Two other features from the previous chapter also fail in window aggregates. DISTINCT and an aggregate-level ORDER BY are not implemented for window functions, so count(DISTINCT x) FILTER (...) OVER (...) raises an error. The table summarizes the differences.
| Feature | In a grouped aggregate | In a window aggregate |
|---|---|---|
| `FILTER (WHERE ...)` | Allowed | Allowed |
| `DISTINCT` inside the call | Allowed | Not implemented |
| `ORDER BY` inside the call | Allowed | Not implemented |
| `FILTER` on `row_number`, `lag`, etc. | Not applicable | Error |
A common workaround for DISTINCT is to compute the distinct values in a subquery or CTE first, then apply the window aggregate to the result. A common workaround for filtering a pure window function is to apply the condition in a subquery with WHERE, or to add the condition to PARTITION BY when you want a separate sequence per condition value.
Filtering on a window result
You cannot reference a window function in WHERE, GROUP BY or HAVING, because those steps run before windows are evaluated. To keep only rows where a window value meets a condition, compute it in a subquery:
SELECT id, customer_id, running_paid_total
FROM (
SELECT
id,
customer_id,
created_at,
sum(amount) FILTER (WHERE status = 'paid')
OVER (PARTITION BY customer_id ORDER BY created_at) AS running_paid_total
FROM orders
) AS t
WHERE running_paid_total >= 50
ORDER BY customer_id, created_at;Here the outer WHERE filters the output, and the inner FILTER filters the aggregate input. They answer different questions and can appear together.
CASE as an alternative
The CASE form works in window aggregates in the same way as in grouped ones:
SELECT
id,
sum(CASE WHEN status = 'paid' THEN amount END)
OVER (PARTITION BY customer_id ORDER BY created_at) AS running_paid_total
FROM orders;It gives the same result as the FILTER version, because sum ignores the NULLs that CASE produces for non-paid rows. The FILTER form keeps the condition separate from the expression being summed. Use CASE when you need to match code that must also run on a database without FILTER.
Summary of rules
- Write
FILTERafter the aggregate's closing parenthesis and beforeOVER. - Every row still appears in the output. Only the aggregate's input shrinks.
- An empty frame gives NULL for
sum,avg,minandmax, and 0 forcount. - Add a tie-breaker or use
ROWSwhen peers would blur a running total. - Do not expect
DISTINCT, aggregateORDER BYor pure window functions to acceptFILTERin a window. - To restrict output rows by a window result, use a subquery.
Exercise
For the orders table, write a query that returns every order together with the number of refunded orders the same customer has placed so far, including the current order. The count must be 0 (not NULL) for customers with no refunds yet, and all orders must appear. Which window frame does your query use by default, and what can go wrong if two orders share the same created_at?
Show answer
SELECT id, customerid, createdat, count(*) FILTER (WHERE status = 'refunded') OVER (PARTITION BY customerid ORDER BY createdat, id) AS refundssofar FROM orders ORDER BY customerid, createdat, id; Because count returns 0 over an empty set, no coalesce is needed. With ORDER BY in the window and no explicit frame, the default is RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW, which includes all peers of the current row. If two orders share the same created_at, each would count the other. Adding id to the window ORDER BY (or using ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) makes the ordering strict, so each row counts only the rows before it plus itself.
Exercise
A colleague writes lag(amount) FILTER (WHERE status = 'paid') OVER (PARTITION BY customerid ORDER BY createdat) to get each order's previous paid amount. Why does it fail, and how would you get the previous paid amount for each paid order?
Show answer
FILTER is accepted only on aggregate functions, and lag is a pure window function, so PostgreSQL reports that FILTER is not implemented for non-aggregate window functions. To get the previous paid amount for each paid order, apply the condition with WHERE in a subquery or CTE that keeps only paid orders, then call lag(amount) OVER (PARTITION BY customerid ORDER BY createdat) on that result. The window then sees only paid rows, so lag returns the previous paid amount.