SQL PARTITION BY with expressions
Any expression can define a partition: calendar buckets, conditional cohorts or normalized keys, evaluated per row before windows run.
- Categoría
- Ventana
- Returns
per-partition value- In this category
- 43 of 79
Sintaxis
SUM(x) OVER (PARTITION BY DATE_TRUNC('month', d)) | COUNT(*) OVER (PARTITION BY CASE WHEN ... END)
Soporte del motor
| Motor | Support | Notas |
|---|---|---|
| SQL Server | Sí | Supported under this name. |
| PostgreSQL | Sí | Supported under this name. |
| MySQL | Sí | MySQL 8.0+; use DATE_FORMAT / YEAR-MONTH expressions |
| SQLite | Sí | SQLite 3.25+; use strftime('%Y-%m', d) |
| Oracle | Sí | Supported under this name. |
Ejemplos
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;
Conviene saberlo
- 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.
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.