SQL aggregates and NULL
How the five engines ignore NULL inside SUM, AVG, COUNT and friends, and what that does to your denominators.
- Kategorie
- Aggregates
- Returns
numeric or bigint- In this category
- 45 of 52
Syntax
COUNT(x) | AVG(x) | SUM(x)
Engine-Unterstützung
| Engine | Support | Notizen |
|---|---|---|
| SQL Server | Ja | Supported under this name. |
| PostgreSQL | Ja | Supported under this name. |
| MySQL | Ja | Supported under this name. |
| SQLite | Ja | Supported under this name. |
| Oracle | Ja | Supported under this name. |
Beispiele
Any engine
SELECT COUNT(*) AS rows_read, COUNT(shipped_at) AS rows_shipped, AVG(total) AS avg_total FROM orders;
SQLite
SELECT SUM(amount), TOTAL(amount) FROM ledger WHERE 0 = 1;
Gut zu wissen
- COUNT(*) counts rows; COUNT(col) counts rows where col is not NULL. The two diverge exactly on NULLs.
- AVG and SUM divide over non-NULL values only, so NULL rows never dilute the result; wrap the column in COALESCE if you want NULLs to count as zero.
- SUM or AVG over an empty or all-NULL group returns NULL, not 0; COUNT returns 0.
- A handy side effect: AVG(flag) over 0/1 values is the fraction of 1s.
Questions about NULL
Why does SUM return NULL for no rows?
The standard defines aggregates over the empty set as NULL, except COUNT; use COALESCE(SUM(x), 0) or SQLite's TOTAL.
Do NULLs lower AVG?
No: AVG ignores them, dividing by the count of present values only.
How do I make NULLs count as zero?
AVG(COALESCE(x, 0)), but decide first whether that is the number you actually want.
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.