// aggregates reference

SQL aggregates and NULL

How the five engines ignore NULL inside SUM, AVG, COUNT and friends, and what that does to your denominators.

카테고리
Aggregates
Returns
numeric or bigint
In this category
45 of 52

구문

COUNT(x) | AVG(x) | SUM(x)

엔진 지원

엔진Support메모
SQL Server 예 Supported under this name.
PostgreSQL 예 Supported under this name.
MySQL 예 Supported under this name.
SQLite 예 Supported under this name.
Oracle 예 Supported under this name.

예시

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;

알아 두면 좋은 정보

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

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.