// aggregates reference

SQL TOTAL function

SQLite's SUM variant that never returns NULL and never fails on integer overflow.

类别
Aggregates
Returns
real
In this category
35 of 52

语法

total(x) | total(x) FILTER (WHERE ...)

引擎支持

引擎Support备注
SQL Server Not built in No built-in equivalent.
PostgreSQL Not built in No built-in equivalent.
MySQL Not built in No built-in equivalent.
SQLite 是 Supported under this name.
Oracle Not built in No built-in equivalent.

示例

SQLite

SELECT total(amount) FROM ledger WHERE account_id = 3;

SQLite

SELECT SUM(amount), TOTAL(amount) FROM ledger WHERE 0 = 1;

值得了解

  • SUM over an empty or all-NULL group returns NULL; TOTAL returns 0.0, no COALESCE needed.
  • TOTAL always returns a REAL, so large integers lose precision past 2^53; SUM throws an integer-overflow error where TOTAL silently floats.
  • Elsewhere the portable pattern is COALESCE(SUM(x), 0).

Questions about TOTAL

TOTAL vs SUM in SQLite?

TOTAL returns 0.0 instead of NULL for empty input and floats instead of erroring on overflow; SUM keeps integers exact.

How do I get TOTAL's behaviour elsewhere?

COALESCE(SUM(x), 0), the standard trick on the other four engines.

Is TOTAL exact for big integers?

No, it is a 64-bit float; beyond 2^53 the low bits are lost.

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: SQLite.

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