SQL SUM
SUM(expression) adds up numeric values. NULLs are ignored.
SELECT SUM(column_or_expression)
FROM table_name
WHERE condition;Summing a column
How many units of all products are in stock, and how many of those are electronics?
SELECT SUM(stock) AS total_units FROM products;
SELECT SUM(stock) AS electronics_units FROM products WHERE category_id = 6;total_units
-----------
1587
(1 row)
electronics_units
-----------------
222
(1 row)
Summing an expression
The argument can be a calculation. The value of all stock is price × stock for each product, added together:
SELECT ROUND(SUM(price * stock), 2) AS stock_value
FROM products;stock_value
-----------
16182.96
(1 row)
Tip: Floating-point numbers such as
24.5and8.75can produce long tails like1398.6000000000001after multiplying. Wrap money results inROUND(…, 2). Real systems often store money as integer cents or asDECIMAL(10,2).
Revenue per order
An order's value is the sum of quantity × price over its items. Prices are in products, quantities in order_items, so we join the two:
SELECT oi.order_id,
SUM(oi.quantity) AS units,
ROUND(SUM(oi.quantity * p.price), 2) AS order_total
FROM order_items AS oi
JOIN products AS p ON p.product_id = oi.product_id
WHERE oi.order_id <= 5
GROUP BY oi.order_id
ORDER BY oi.order_id;order_id | units | order_total
---------+-------+------------
1 | 13 | 34.49
2 | 5 | 147.5
3 | 8 | 49.79
4 | 5 | 19.45
5 | 8 | 164.8
(5 rows)
Revenue per category
The same idea, grouped by category — and limited to orders that were not cancelled:
SELECT c.name AS category,
ROUND(SUM(oi.quantity * p.price), 2) AS revenue
FROM order_items AS oi
JOIN orders AS o ON o.order_id = oi.order_id
JOIN products AS p ON p.product_id = oi.product_id
JOIN categories AS c ON c.category_id = p.category_id
WHERE o.status <> 'cancelled'
GROUP BY c.category_id
ORDER BY revenue DESC;category | revenue
------------+--------
Electronics | 2153.35
Home | 671
Beverages | 470.65
Bakery | 349.15
Books | 349
Snacks | 114.72
Produce | 68.19
Dairy | 56.65
(8 rows)
Don't worry if the joins look dense — they are explained step by step later. The key point: SUM adds up whatever expression you give it, per group.
SUM of nothing is NULL
When no rows match, SUM returns NULL, not 0. SQLite's TOTAL() returns 0.0 instead; portable code uses COALESCE:
SELECT SUM(stock) AS sum_result,
TOTAL(stock) AS total_result,
COALESCE(SUM(stock), 0) AS coalesced
FROM products
WHERE price > 1000;sum_result | total_result | coalesced
-----------+--------------+----------
NULL | 0 | 0
(1 row)
Test yourself
What does SUM(price * stock) compute?
- The sum of prices times the sum of stock
- The sum over rows of price × stock
- An error, SUM takes only a column
- The average stock value
What does SUM(col) return when no rows match?
- 0
- NULL
- An error
- An empty string