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.
- Categoría
- Ventana
- Returns
bigint- In this category
- 22 of 79
Sintaxis
COUNT(*) OVER (PARTITION BY g) | COUNT(*) OVER (ORDER BY d) | COUNT(*) OVER ()
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
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;
Conviene saberlo
- 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.
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.