SQL window function performance
Each distinct window definition may force a sort of the full input; frames and partitioning decide how much work each row costs.
- Kategorie
- Fenster
- Returns
n/a (performance)- In this category
- 78 of 79
Syntax
-- supporting index on (partition_col, order_col) CREATE INDEX ix ON orders (customer_id, order_date DESC)
Engine-Unterstützung
| Engine | Support | Notizen |
|---|---|---|
| SQL Server | Ja | Supported under this name. |
| PostgreSQL | Ja | Supported under this name. |
| MySQL | Ja | MySQL 8.0+ |
| SQLite | Ja | SQLite 3.25+ |
| Oracle | Ja | Supported under this name. |
Beispiele
Any engine
-- pre-aggregate to shrink the windowed row set
WITH daily AS (
SELECT order_date, customer_id, SUM(amount) AS amount
FROM orders
GROUP BY order_date, customer_id
)
SELECT customer_id, order_date, amount,
SUM(amount) OVER (PARTITION BY customer_id ORDER BY order_date) AS running
FROM daily;
Gut zu wissen
- Sort cost multiplies: N different PARTITION BY/ORDER BY combinations can mean N sorts. Use the same combination wherever the meaning allows.
- An index on (partition columns, ORDER BY columns) lets the engine read rows already in window order and skip the sort, provided the query can use that index for the scan.
- On SQL Server row-mode plans, frames written as ROWS use an in-memory window spool while the default RANGE frame uses an on-disk one, so writing ROWS UNBOUNDED PRECEDING explicitly can speed up running totals. Batch-mode Window Aggregate (2016+, columnstore or 2019 batch mode on rowstore) avoids the spool.
- Filter early, window late: apply WHERE and pre-aggregate in a CTE before the window pass so the sort touches fewer, smaller rows.
Questions about Window Function Performance
Why is my window query slower than GROUP BY?
GROUP BY hashes and collapses; windows sort per partition and keep every row. If you only need group numbers, GROUP BY (joined back if needed) avoids the per-row work entirely.
How do I make several window functions share one sort?
Give them the same PARTITION BY and ORDER BY (a named WINDOW makes that easy to keep). Functions with an identical window, or one whose ordering is a prefix of another's, can share one sort.
Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.
Related on SQLly
Cheat sheets for the engines that have it: SQL Server, PostgreSQL, MySQL, SQLite, Oracle.
Functions your engine actually has
SQLly's completion lists the built-in functions of the engine you're connected to, whether that's SQL Server, PostgreSQL, MySQL, SQLite or Oracle. Hover a function for help, and signature hints show each argument as you type.