How to Implement Efficient Window Queries
Write efficient SQL window functions: choose the right frame, index the partition and order, and avoid sorts that dominate the plan.
On this page
Introduction
Window functions compute values across a set of rows related to the current row: a running total, a rank within a group, the value from a previous row. They are powerful and easy to make slow, because a window over a large partition requires the rows to be brought into order, and without a suitable index that means a sort that can dominate the whole query and spill to disk.
This tutorial covers writing window queries that the planner can serve from an index, separating the window from the filter, choosing the frame that matches the intended semantics, and reading the plan to find the sort. The examples use PostgreSQL, whose window frame defaults and explain output illustrate the issues.
Compute the window, then filter
Window functions are evaluated after WHERE, GROUP BY, and HAVING, so they cannot appear in a WHERE clause directly. To rank and then keep the top few, compute the rank in a subquery or CTE and filter in the outer query. This is not just syntax: the outer filter lets the planner know it can stop early in some cases and keeps the plan readable.
Push as much ordinary filtering as possible inside the subquery, before the window is computed, so the window runs over a smaller set. Filtering by a range on the partition key or a status inside the subquery reduces the rows the window must order. Only the window-derived predicate, such as rank <= 3, belongs outside.
-- rank inside, filter outside; ordinary filters pushed down
SELECT * FROM (
SELECT customer_id, id, total,
row_number() OVER (PARTITION BY customer_id ORDER BY created_at DESC) AS rn
FROM orders
WHERE created_at >= now() - interval '90 days' -- narrows the rows the window orders
) t
WHERE rn <= 3;
Index the partition and order
A window that partitions by customer_id and orders by created_at can be computed from a scan that is already ordered by that partition and order, avoiding a sort. A composite index on (customer_id, created_at DESC) provides exactly that order, so the window reads rows in order and the Sort node disappears. Without the index, the planner reads all rows and sorts them, which is where a window query becomes expensive.
Match the index to the window’s PARTITION BY and ORDER BY, in that order. The partition columns lead because the window resets per partition, and the order column follows. When several windows share a partition but differ in order, one index can serve the shared partition and the planner sorts within partitions for the others; minimize the number of distinct orderings to keep the plan simple.
CREATE INDEX CONCURRENTLY idx_orders_customer_created
ON orders (customer_id, created_at DESC);
-- the same order the window needs, so no Sort is required
SELECT customer_id, total,
row_number() OVER (PARTITION BY customer_id ORDER BY created_at DESC) AS rn
FROM orders;
Choose the frame that matches intent
A running total uses the default frame RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW for an ordered window. That frame includes all rows with the same ordering value as the current row, so ties at the same value are added together. If the ordering column has duplicates and you want the total to advance one row at a time, use ROWS instead of RANGE, which counts physical rows rather than peer groups.
Moving windows use a bounded frame, such as ROWS BETWEEN 6 PRECEDING AND CURRENT ROW for a seven-row moving average. The frame determines which rows contribute, and an unintuitive frame is a frequent source of wrong results that look plausible. Write the frame explicitly when it is not the default, and document why, because the default’s tie behavior is subtle.
-- running total advancing one row per tie (ROWS), not merging ties (RANGE)
SELECT id, amount,
sum(amount) OVER (ORDER BY id ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS running
FROM payments;
-- 7-row moving average
SELECT id, value,
avg(value) OVER (ORDER BY id ROWS BETWEEN 6 PRECEDING AND CURRENT ROW) AS ma7
FROM samples;
Read the plan for sorts and window nodes
The plan shows a WindowAgg node for each window function and any Sort node the planner needed to provide the order. An index that supplies the order removes the Sort, so the plan goes straight from an Index Scan to the WindowAgg. If a Sort remains and is large, it may spill to disk, indicated by disk usage in the node; raising work_mem for that query or adding the index that supplies the order removes the spill.
Multiple windows over the same partition can share one sort if their orderings match, which the planner does automatically when possible. Distinct orderings force distinct sorts, so a query with three different ORDER BY clauses in its windows sorts three times. Reduce the number of distinct orderings or split the query, and check the plan for more Sort nodes than expected.
WindowAgg (actual rows=...)
-> Index Scan using idx_orders_customer_created on orders
-- no Sort node: the index supplies (customer_id, created_at DESC) order
Test results and the plan
Test the frame behavior with tied ordering values: assert that a running total with RANGE merges ties while one with ROWS does not, which pins the semantics. Test that a moving average of a known series matches a hand-computed value at the start, middle, and end of the series. Test that the plan has no large Sort for the indexed window, which guards against an index being dropped or the query drifting from the index’s order.
psql -d app -c "EXPLAIN (ANALYZE, BUFFERS) SELECT ... row_number() OVER (PARTITION BY customer_id ORDER BY created_at DESC) ... FROM orders;"
# assert there is no Sort node, and no 'Disk:' line in a Sort if one is present
Common pitfalls
Filtering on a window function directly in WHERE, using the default RANGE frame where ties should not merge, a window without an index on the partition and order columns so a sort dominates, too many distinct orderings forcing repeated sorts, and a large sort spilling to disk are the recurring mistakes. Compute-then-filter, an explicit frame, a matching index, fewer orderings, and reading the plan address them.
Conclusion
Efficient window queries are about the order the rows arrive in. Compute the window in a subquery and filter outside, index the partition and order columns so the planner skips the sort, choose the frame that matches the intended tie behavior, and read the plan for sorts and spills. Self-check by asserting the results for tied and moving windows and that the plan has no large sort. When the index supplies the order, a window is a scan, not a sort.
Sources: PostgreSQL: Window function calls and frames, PostgreSQL: Window functions tutorial, PostgreSQL: Window function performance.
FAQ
- Why can't I filter on a window function in WHERE?
- Window functions are computed after WHERE, GROUP BY, and HAVING, so they are not available to WHERE. Compute the window in a subquery or CTE and filter the outer query, which lets the planner push other filters down first.
- When do I need an explicit frame?
- The default frame for an ordered window is RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW, which groups tied rows together. If ties should be counted separately, use ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW so each row advances the running total by one.
Report a problem with this articleOpens a pre-filled issue on GitHub.