SQL SUM function
Adds up the non-null values of an expression across a group. The result type and the empty-group result both differ from what most people expect.
- Category
- Aggregates
- Returns
numeric; int input gives int on SQL Server, bigint on PostgreSQL, DECIMAL on MySQL- In this category
- 2 of 52
Syntax
SUM(expression)
SUM(DISTINCT expression)
Each block is a separate form. The support table and the examples show which engine takes which.
Engine support
| Engine | Support | Notes |
|---|---|---|
| SQL Server | Yes | Supported under this name. |
| PostgreSQL | Yes | Supported under this name. |
| MySQL | Yes | Supported under this name. |
| SQLite | Yes | Supported under this name. |
| Oracle | Yes | Supported under this name. |
Examples
Any engine
SELECT COALESCE(SUM(amount), 0) AS total FROM payments;
SQL Server
SELECT SUM(CAST(quantity AS BIGINT)) AS total_items FROM order_items;
Good to know
- SUM skips NULLs: 10, NULL and 5 sum to 15. It only returns NULL when every value in the group is NULL or the group is empty.
- Summing zero rows returns NULL, not 0. Wrap it: COALESCE(SUM(amount), 0).
- On SQL Server, SUM of an int column returns int and fails with an arithmetic overflow past 2,147,483,647. CAST the column to BIGINT first. PostgreSQL widens int sums to bigint, and bigint sums to numeric, so it does not overflow there.
Questions about SUM
Why does SUM return NULL instead of 0?
An aggregate over zero rows has nothing to add, and SQL's answer to nothing is NULL. Use COALESCE(SUM(x), 0) when the caller expects a number.
How do I sum only rows that match a condition?
SUM(CASE WHEN status = 'paid' THEN amount END) works everywhere. PostgreSQL and SQLite 3.30+ also have the FILTER clause: SUM(amount) FILTER (WHERE status = 'paid').
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.