// window reference

SQL PARTITION BY in window functions

Divides the result set into partitions; each window function computes independently per partition and resets at its boundaries.

카테고리
창
Returns
per-partition value
In this category
42 of 79

구문

SUM(x) OVER (PARTITION BY g) | ROW_NUMBER() OVER (PARTITION BY g1, g2 ORDER BY d)

엔진 지원

엔진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.

예시

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;

알아 두면 좋은 정보

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

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.