SQL PARTITION BY in window functions
Divides the result set into partitions; each window function computes independently per partition and resets at its boundaries.
- Categoría
- Ventana
- Returns
per-partition value- In this category
- 42 of 79
Sintaxis
SUM(x) OVER (PARTITION BY g) | ROW_NUMBER() OVER (PARTITION BY g1, g2 ORDER BY d)
Soporte del motor
| Motor | Support | Notas |
|---|---|---|
| SQL Server | Sí | Supported under this name. |
| PostgreSQL | Sí | Supported under this name. |
| MySQL | Sí | MySQL 8.0+ |
| SQLite | Sí | SQLite 3.25+ |
| Oracle | Sí | Supported under this name. |
Ejemplos
PostgreSQL
SELECT department, employee_id, salary,
AVG(salary) OVER (PARTITION BY department) AS dept_avg,
COUNT(*) OVER (PARTITION BY EXTRACT(YEAR FROM hire_date)) AS hires_that_year
FROM employees;
Conviene saberlo
- PARTITION BY takes expressions, not just columns: date_trunc('month', d) on PostgreSQL (or YEAR(d), MONTH(d) on SQL Server and MySQL) partitions by month with no CTE.
- NULLs form their own partition; rows with NULL keys get window values computed among themselves rather than being excluded.
- PARTITION BY never changes row count, the closest thing to 'GROUP BY that does not collapse'. Sorting the output still needs an outer ORDER BY.
Questions about PARTITION BY
PARTITION BY or GROUP BY: which do I need?
GROUP BY when one row per group is the answer; PARTITION BY when every row must stay and carry its group's statistic. They can coexist in one query.
Can I PARTITION BY multiple columns?
Yes, comma-separated, and any expression: PARTITION BY region, EXTRACT(YEAR FROM order_date) (YEAR(order_date) on SQL Server). The partition key is the combination of all of them.
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.