How to Speed Up Window Function Queries
Reduce the cost of window functions by indexing for their ordering, shrinking the frame, and aggregating in stages.
On this page
Introduction
Window functions express per-group computation without collapsing rows: rank within a partition, running totals, moving averages, lag and lead. They are expressive and often replace a self-join or a correlated subquery, but they can be slow because the database must sort each partition and, for a moving frame, revisit rows. This article explains where the cost comes from, how to read the plan, and the concrete changes that turn a slow window query into a fast one: the right index, a tighter frame, and pre-aggregation.
Why Window Functions Get Slow
A window function requires the rows of each partition to be in the order the window specifies. If no index provides that order, the database sorts: an O(n log n) step over the whole input, or worse if the sort spills to disk. Then, for a frame such as ROWS BETWEEN 1 PRECEDING AND 1 FOLLOWING or a running total, the engine must process the frame per row, which for a large unbounded frame means scanning back over already-seen rows.
Two costs therefore dominate: the sort, and the per-row frame scan. The first is fixed by matching the index to the window ordering; the second by narrowing the frame or precomputing the aggregate. Reading the plan tells you which one is biting.
Reading the Plan
Run EXPLAIN and look for the window node and any sort below it. A sort over a large row estimate, especially one that spills to disk, is the first thing to remove. A window node with a huge frame and high loop count is the second. Statistics matter here: stale statistics can make the planner choose a worse join order that feeds far more rows into the window than necessary. After any change, verify the fix by re-running EXPLAIN and checking that the sort is gone and the row count entering the window has dropped, rather than assuming the change helped.
EXPLAIN (ANALYZE, BUFFERS)
SELECT
user_id,
created_at,
amount,
sum(amount) OVER (PARTITION BY user_id ORDER BY created_at) AS running_total,
row_number() OVER (PARTITION BY user_id ORDER BY created_at DESC) AS recency
FROM orders
WHERE created_at >= now() - interval '30 days';
-- Look for: Sort Method (external merge = spilled disk), and the row counts
-- entering the WindowAgg node. If rows entering far exceed rows returned,
-- the partition key or the filter predicate is not doing its job.
Indexing for the Window Ordering
Provide the ordering the window needs so the engine can read rows already sorted. For PARTITION BY user_id ORDER BY created_at, an index on (user_id, created_at) matches both the partition and the order, so no explicit sort is needed. If the query also filters on a range of dates, an index on (user_id, created_at) still helps, and a covering index that includes the aggregated column avoids a heap fetch.
-- Matches PARTITION BY user_id ORDER BY created_at
CREATE INDEX idx_orders_user_created
ON orders (user_id, created_at);
-- Covering variant that also returns amount without reading the heap
CREATE INDEX idx_orders_user_created_amount
ON orders (user_id, created_at) INCLUDE (amount);
-- For a query ordered by created_at DESC per user, the same index serves the
-- backward scan; PostgreSQL can walk an ascending index in reverse.
Reducing the Frame
Default frames are larger than people assume. With ORDER BY, the default frame is RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW, which for a running total still requires accumulating all preceding rows within the partition; that is fine when you want a running total and wasteful when you want a moving window. Specify the narrowest frame that answers the question: ROWS BETWEEN 6 PRECEDING AND CURRENT ROW for a seven-day moving sum.
Filter before the window, not after. A query that computes a window over the whole history and then keeps the last thirty days has already paid for the history. Push the date filter into the scan so only the relevant rows enter the window. The filter and the window ordering are easier to satisfy together, which is another reason to align the index with both.
Aggregating in Stages
Sometimes the right move is not to make the window faster but to avoid it. If you need a per-user daily total and then a running total of those daily totals, aggregate by (user_id, day) once and apply the window over that smaller set. The second window then processes one row per day per user instead of one row per order. Materialize the intermediate with a CTE or a materialized view if it is reused.
For counts and distinct counts over large partitions, consider whether an approximate or a pre-aggregated table is acceptable. Exact distinct-count windows are expensive; a summary table maintained on write can answer the same question with an indexed lookup. Choose the trade-off explicitly rather than paying the window cost on every query.
When to Materialize
If a window result is stable and read frequently, compute it once into a materialized view and refresh it on a schedule. A summary table of ranks, running totals or moving averages turns a sort-heavy query into a plain indexed read for every consumer. Refresh cost is paid once instead of per query, and you can refresh concurrently to avoid blocking readers.
Keep the materialized result small: store the computed columns, not the whole base table, and index it for the access pattern that reads it. Track its freshness, because a stale summary table silently serves wrong numbers. Refresh cadence is a decision about acceptable staleness, not a technical default.
Conclusion
Window functions are slow for two reasons: a sort that the index should have avoided, and a frame processed per row over too many rows. Match the index to the partition and ordering, push filters before the window, narrow the frame to what the question needs, and pre-aggregate in stages so the window runs over the smallest set that answers it. For stable, hot results, materialize them. Read the plan to see which cost is real, and fix that one rather than tuning by guesswork.
Sources: PostgreSQL: window functions, PostgreSQL: EXPLAIN, Window function.
FAQ
- Why does my window query sort when I have an index?
- The index must match the window partition and ordering together. An index on created_at alone does not provide the per-user order, so the engine still sorts. Use a composite index on (partition_column, order_column).
- Does a smaller frame always make a window faster?
- Usually, because the engine revisits fewer preceding rows per output row. But if the query filters after the window instead of before it, the window still processes all rows. Push filters into the scan so the frame works over the relevant subset only.
Report a problem with this articleOpens a pre-filled issue on GitHub.