// window reference

SQL PARTITION BY with expressions

Any expression can define a partition: calendar buckets, conditional cohorts or normalized keys, evaluated per row before windows run.

類別
視窗
Returns
per-partition value
In this category
43 of 79

語法

SUM(x) OVER (PARTITION BY DATE_TRUNC('month', d)) | COUNT(*) OVER (PARTITION BY CASE WHEN ... END)

引擎支援

引擎Support備註
SQL Server 是 Supported under this name.
PostgreSQL 是 Supported under this name.
MySQL 是 MySQL 8.0+; use DATE_FORMAT / YEAR-MONTH expressions
SQLite 是 SQLite 3.25+; use strftime('%Y-%m', d)
Oracle 是 Supported under this name.

範例

PostgreSQL

SELECT order_id, order_date, amount,
       SUM(amount) OVER (PARTITION BY date_trunc('month', order_date)
                         ORDER BY order_date) AS mtd_amount
FROM orders;

小知識

  • The same expression logic applies in ORDER BY inside OVER: partitioning by month and ordering by day gives a running total per month.
  • Bucketing with CASE creates cohorts on the fly: PARTITION BY CASE WHEN amount > 1000 THEN 'big' ELSE 'small' END windows over the two tiers.
  • Keep partition expressions simple enough for the engine to match to an index when performance matters; a function on the partition key cannot use a plain index on the column.

Questions about PARTITION BY Expressions

Can I partition by a column I compute in the same SELECT?

Not by its alias: window inputs are the underlying rows, so repeat the expression (or compute it in a CTE first). Repeating it is also what the parser expects.

Does an expression partition defeat indexes?

It can. Partitioning on d uses an index on d; partitioning on DATE_TRUNC('month', d) generally cannot. For hot paths, materialize the bucket column and index it.

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.