// window reference

SQL COUNT with OVER

Counts rows in the window frame or partition and attaches the number to every row: partition size, running count or grand total as needed.

Категория
Окно
Returns
bigint
In this category
22 of 79

Синтаксис

COUNT(*) OVER (PARTITION BY g) | COUNT(*) OVER (ORDER BY d) | COUNT(*) OVER ()

Поддержка движка

Движок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

SELECT department, employee_id,
       COUNT(*) OVER (PARTITION BY department) AS dept_size
FROM employees;

Any engine

SELECT order_id, created_at,
       COUNT(*) OVER (ORDER BY created_at) AS orders_so_far,
       COUNT(*) OVER () AS total_orders
FROM orders;

Полезно знать

  • COUNT(*) OVER (ORDER BY d) is a running count: the default frame ends at the current row, so every row shows how many rows came up to it.
  • COUNT(expr) counts non-NULL values only, in window form too: COUNT(x) OVER () can be smaller than COUNT(*) OVER () on sparse columns.
  • COUNT(DISTINCT x) OVER (...) is rejected by SQL Server, PostgreSQL, MySQL and SQLite. Oracle runs it, but only without ORDER BY in the OVER clause.

Questions about COUNT OVER

How do I get the group size on every row?

COUNT(*) OVER (PARTITION BY group_col): the same number repeats on every row of the group without collapsing them, unlike GROUP BY + join.

Why is my running COUNT the same on tied rows?

The default frame is RANGE up to CURRENT ROW, which includes peers. Tied rows share the count through the last peer; use COUNT(*) OVER (ORDER BY d ROWS UNBOUNDED PRECEDING) for strict row-by-row counting.

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.