SQL SUM
SUM totals up the values in a numeric column.
Basic example
SQL
SELECT SUM(total) AS revenue FROM orders;
Per-group totals
SQL
SELECT category, SUM(price * stock) AS inventory_value FROM products GROUP BY category ORDER BY inventory_value DESC;
SUM and NULLs
- NULL values are skipped — they don't pull the total down.
- SUM over zero rows returns
NULL, not0. Wrap inCOALESCEif you need a number:
SQL
SELECT COALESCE(SUM(total), 0) AS revenue FROM orders WHERE created_at >= '2026-01-01';
Conditional SUM
You can sum only rows matching a condition with CASE:
SQL
SELECT SUM(CASE WHEN status = 'paid' THEN total ELSE 0 END) AS paid_revenue, SUM(CASE WHEN status = 'refund' THEN total ELSE 0 END) AS refunds FROM orders;
Tip: For currency, use
DECIMAL not FLOAT — float SUMs accumulate rounding errors. Even cents shouldn't be stored as floats.Example
Exercise
Force 0 instead of NULL when there are no rows to sum.
SELECT
(SUM(total), 0) FROM orders WHERE 1=0;
Eight letters; the NULL-replacement function.
Discussion
Loading…