Sub topic 15
Performance notes and dialect differences
This chapter assumes you know the OVER clause, PARTITION BY, window ORDER BY, frames, and how to filter window results with a CTE. It covers what a window function costs the database and where the major databases behave differently. Use it when a window query is slow or when you port one between systems.
What a window query costs
A window function needs its rows grouped by partition and sorted by the window's ORDER BY. Most of the cost comes from that sort. Once rows arrive in order, the engine streams through each partition and computes the function.
For a window such as PARTITION BY region ORDER BY sale_date, id, the engine does three things:
- It reads the input rows after FROM, JOIN, WHERE, GROUP BY and HAVING have run.
- It sorts them by (
region,sale_date,id), unless an index already delivers that order. - It walks the sorted rows and computes each function over its frame.
Three things follow from this:
- Sort size matters. A sort that fits in memory is fast. A sort that spills to disk is slow. In PostgreSQL the limit is
work_mem. SQL Server and Oracle use memory grants and temporary space. - Each distinct window may need its own sort. If one query uses
OVER (PARTITION BY region ORDER BY amount)andOVER (PARTITION BY salesperson ORDER BY sale_date), the engine sorts twice. - Fewer input rows means less work. Anything that shrinks the input before the window step helps.
Reducing the sort
Match an index to the window
An index whose leading columns match the PARTITION BY columns, followed by the ORDER BY columns, can supply rows already in order. The engine can then skip the sort.
CREATE INDEX idx_sales_region_date_id
ON sales (region, sale_date, id);
EXPLAIN (ANALYZE, BUFFERS)
SELECT
region,
sale_date,
amount,
SUM(amount) OVER (
PARTITION BY region
ORDER BY sale_date, id
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
) AS running_total
FROM sales;This is PostgreSQL syntax. Look in the plan for a WindowAgg node. If a Sort node sits directly under it, the index was not used for ordering. The planner may still choose a sort when the table is small or when it reads most of the table, because a sequential scan plus a sort can be cheaper than a full index scan. The index helps most when the query also filters or limits rows.
Share one window between functions
Functions with identical PARTITION BY and ORDER BY clauses usually share one sort. Functions with different clauses do not. Two habits keep sorts down:
- Make equivalent windows textually identical, or name them with the WINDOW clause where it is supported.
- Where you control the design, order several windows by a common prefix. A sort by (
region,sale_date) can serve a window that partitions byregiononly.
Filter before the window step
A WHERE clause that removes rows before the window step reduces both the sort and the computation. That is only correct if removing those rows does not change the answer. Removing a whole partition is always safe. Removing individual rows changes what the window sees.
-- Safe to filter early: the region filter drops whole partitions.
SELECT region, id, amount,
ROW_NUMBER() OVER (PARTITION BY region ORDER BY amount DESC) AS rn
FROM sales
WHERE region = 'West';
-- Not the same query: filtering by date first renumbers the remaining rows.
SELECT region, id, amount,
ROW_NUMBER() OVER (PARTITION BY region ORDER BY amount DESC) AS rn
FROM sales
WHERE sale_date >= DATE '2026-01-01';Optimizers know this rule. A filter on a PARTITION BY column outside a subquery can be pushed inside it. A filter on any other column cannot be pushed past the window, so the engine computes the window over all rows first.
Top-N per group
The filter rn <= 3 on a ROW_NUMBER result must run after the window step, so a naive plan numbers every row and then discards most of them. PostgreSQL 15 and later can stop early. A "run condition" lets the WindowAgg node quit a partition once rn exceeds the limit. Other engines vary, so read the plan.
Two alternatives can beat the window approach when there are few groups and many rows per group:
- PostgreSQL's
DISTINCT ONhandles the top-1 case. - A lateral join that fetches the top three rows per group with
ORDER BY amount DESC LIMIT 3can use an index on (region,amount) and read only the rows it needs.
The window version is still the best default. It is portable and easy to read.
Frame choice affects speed
The frame decides how much work each row requires.
ROWScounts physical rows. It is cheap and has simple, predictable semantics.RANGEmust find all peers (rows with the same ORDER BY value), which takes extra work.- A frame that ends at the current row, such as a running total, can be computed incrementally by adding one row at a time.
- A sliding frame, such as
ROWS BETWEEN 2 PRECEDING AND CURRENT ROW, is cheap for small widths. Some engines computeSUMandCOUNTby adding the entering row and subtracting the leaving row. They may recomputeMINandMAXover the whole frame, which is slow for very wide frames. - A frame of
UNBOUNDED PRECEDINGtoUNBOUNDED FOLLOWINGgives every row in the partition the same value. The engine only needs to compute it once per partition.
Dialect differences
All five databases covered here support the core features: OVER, PARTITION BY, ORDER BY, the ranking functions, LAG, LEAD, and aggregate window functions. The differences appear in the edges.
| Feature | PostgreSQL | MySQL 8+ | SQL Server | SQLite 3.25+ | Oracle |
|---|---|---|---|---|---|
| `WINDOW` clause | Yes | Yes | No | Yes | Check your version |
| `GROUPS` frame | 11+ | No | No | Yes (3.28+) | No |
| `RANGE` with numeric offsets | 11+ | Yes | No, only UNBOUNDED and CURRENT ROW | Yes | Yes |
| `NULLS FIRST` / `NULLS LAST` | Yes | No | No | Yes (3.30+) | Yes |
| `IGNORE NULLS` in LAG, LEAD, FIRST_VALUE, LAST_VALUE | No | No | 2022+ | No | Yes |
| Default placement of NULLs in ASC order | Last | First | First | First | Last |
Check the version-specific entries against your own release notes before relying on them. Two items in the table cause most porting bugs.
Where NULLs sort
A window ORDER BY on a nullable column puts NULLs first in some databases and last in others. This changes ROW_NUMBER, RANK, LAG, LEAD, and running totals. A portable way to control it is to add a sort key that puts NULLs where you want them:
SELECT
id,
due_date,
ROW_NUMBER() OVER (
ORDER BY
CASE WHEN due_date IS NULL THEN 1 ELSE 0 END,
due_date
) AS rn
FROM tasks;This puts rows with a due_date first, in date order, and rows without one last. It works in all five databases. It can prevent an index from supplying the order, so measure it on large tables.
Reusing a window without the WINDOW clause
Where the WINDOW clause is missing, repeat the definition in each function. The meaning is identical.
SELECT
region,
sale_date,
amount,
SUM(amount) OVER (
PARTITION BY region
ORDER BY sale_date, id
ROWS UNBOUNDED PRECEDING
) AS running_total,
AVG(amount) OVER (
PARTITION BY region
ORDER BY sale_date, id
ROWS UNBOUNDED PRECEDING
) AS running_avg
FROM sales;Other differences worth knowing
- DISTINCT inside window aggregates.
COUNT(DISTINCT x) OVER (...)is rejected by PostgreSQL and SQL Server. The usual workaround is aDENSE_RANKcomputation or a separate subquery. - Older versions. SQL Server added
LAG,LEAD, and full frame support in 2012. Earlier versions have only the ranking functions and unframed aggregates. MySQL has no window functions before 8.0, and SQLite has none before 3.25. - Ordering without a total order. If the window ORDER BY has ties,
ROW_NUMBERassigns tied rows in an unspecified order. The assignment can change between runs, databases, or plans. Add a unique tiebreaker such asid.
A diagnostic routine
When a window query is slow, work through these steps in order:
- Read the plan. Find the sort feeding the window node and check whether it spills to disk.
- Count the distinct windows. Merge those that can be merged.
- Move any safe filters, especially on partition columns, in front of the window step.
- Check whether an index on the partition and order columns matches the window.
- Replace implicit
RANGEframes with explicitROWSframes when ties do not matter. - For top-N with few groups and large partitions, compare against a lateral join.
Exercise
A query computes SUM(amount) OVER (PARTITION BY region ORDER BY sale_date) on SQL Server, and it is slow on a large table. The sale_date column has many ties within each region. Name two changes you would try, and say which of them can change the results.
Show answer
First, add an index on (region, sale_date) so the engine can read rows in window order and skip the sort. This does not change results. Second, add an explicit frame, ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW, to avoid the default RANGE frame and its spooling. This can change results because the default RANGE frame includes all tied rows on the same date, while ROWS stops at the current physical row. To make the ROWS result deterministic, also add a tiebreaker such as id to the ORDER BY.
Exercise
You must port a query that uses ORDER BY score DESC NULLS LAST inside a window to MySQL 8. What do you write instead?
Show answer
MySQL has no NULLS LAST, so add a sort key that places NULLs last: ORDER BY CASE WHEN score IS NULL THEN 1 ELSE 0 END, score DESC. Rows with a score sort first, from highest to lowest, and rows with a NULL score come last.