Function or operator · Grouping and calculating

SUM

SUM adds up numeric values and ignores NULL. If there is no known value at all, it returns NULL rather than zero.

SUM example

We want to know how many units are in stock in each category. The groups are formed by category and SUM adds up the stock of their products.

SQL
SELECT category, SUM(stock) AS units
FROM products
GROUP BY category
ORDER BY units DESC, category ASC;

The overall stock adds up to 81. Splitting it by category shows where that total comes from and also keeps the group with zero units.

Check the result with small data

The two sales of Books belong to the same category.

Self-contained query · SQLite
WITH sales(category, units) AS (
  VALUES ('Books', 2), ('Books', 3), ('Audio', 1)
)
SELECT category, SUM(units) AS total
FROM sales GROUP BY category ORDER BY category;
Query result
categorytotal
Audio1
Books5

SUM adds up the quantities in each group; it does not count how many sales there were. For Books it returns five units from two rows.

Check your understanding: What value would COUNT(*) show for Books?

Show answer

2: COUNT(*) counts the two Books rows, not the five units.

How SUM is used

Do not add up a column out of habit. First check what each row represents. If an order header repeats its total when joined to several lines, adding up that total after the JOIN will double-count it.

What changes from case to case

Query with no matches
SELECT SUM(total) AS total
FROM orders
WHERE status = 'returned';

Since there is no order with that status, SUM returns NULL. Use COALESCE(SUM(total), 0) only when “no rows” should mean zero for the business.

Common mix-ups with SUM

Adding up after a JOIN has multiplied the rows

Before aggregating, check the granularity: one row per order, per product or per line. If the JOIN produces several rows for the same order, its total can be counted several times. Aggregate at the right level first, or add up the order lines themselves.