iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

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, not 0. Wrap in COALESCE if 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

Example
SELECT SUM(total) AS revenue
FROM orders;
Try it Yourself »

Exercise

Force 0 instead of NULL when there are no rows to sum.

SELECT (SUM(total), 0) FROM orders WHERE 1=0;

Test yourself

Q1. SUM skips…
Q2. To force 0 instead of NULL for empty sets use…
Q3. For money columns, prefer…

Discussion

Loading…