aggregate

SUM

Adds up all non-NULL numeric values in a column or expression. Returns NULL (not 0) if every input row is NULL or the result set is empty.

SUM([DISTINCT] numeric_expression)

Parameters / Modifiers

Parameter Purpose
DISTINCT Sum only unique values, dropping duplicates first
OVER (...) Use as a window function for running totals
FILTER (WHERE ...) Postgres: sum only rows matching a predicate

Examples

SELECT SUM(amount) FROM payments;

Total payment amount across all rows

SELECT product_id, SUM(qty) FROM order_items GROUP BY product_id;

Total units sold per product

SELECT COALESCE(SUM(amount), 0) FROM payments WHERE user_id = 42;

Guarantees 0 instead of NULL when the user has no payments

SELECT SUM(amount) OVER (ORDER BY paid_at) AS running FROM payments;

Cumulative running total ordered by date

Dialect notes / Gotcha

SUM of no rows returns NULL, not 0 — wrap in COALESCE(SUM(...), 0). Integer overflow can occur in MySQL; cast to DECIMAL or BIGINT for large aggregations.

Related functions

← All SQL functions · SQL cheat sheet · Window functions · PostgreSQL cheat sheet