// window reference

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.

类别
窗口
Returns
n/a (performance)
In this category
78 of 79

语法

-- supporting index on (partition_col, order_col)
CREATE INDEX ix ON orders (customer_id, order_date DESC)

引擎支持

引擎Support备注
SQL Server 是 Supported under this name.
PostgreSQL 是 Supported under this name.
MySQL 是 MySQL 8.0+
SQLite 是 SQLite 3.25+
Oracle 是 Supported under this name.

示例

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;

值得了解

  • 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.

Cheat sheets for the engines that have it: SQL Server, PostgreSQL, MySQL, SQLite, Oracle.

// fewer lookups

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.