SQL course menu
SQL SUM(): Add Up Values in a Column
Learn the SQL SUM function: total a column, sum calculated values, sum per group with GROUP BY, conditional sums with CASE, and why SUM returns NULL when no rows match.
On this page
SUM adds up the values in a column: total revenue, total payroll, total units in stock. Like COUNT, it is an aggregate function that turns many rows into a single number.
The example tables#
employees
orders
Syntax#
SELECT SUM(column)
FROM table_name
WHERE condition;SUM only works on numeric columns.
Total of a column#
SELECT SUM(salary) AS total_payroll
FROM employees;total_payroll
-------------
318000Total of matching rows#
Revenue from February onwards:
SELECT SUM(amount) AS revenue
FROM orders
WHERE order_date >= '2026-02-01';revenue
-------
770That is 120 + 560 + 90. Order 101 from January was filtered out before summing.
Sum of a calculation#
SUM can add up any expression, evaluated row by row. The total value of stock in the products table is each product's price times its stock, summed:
SELECT SUM(price * stock) AS stock_value
FROM products;stock_value
-----------
868500Sum per group#
SELECT department, SUM(salary) AS payroll
FROM employees
GROUP BY department
ORDER BY payroll DESC;department | payroll
------------+--------
Engineering | 159000
Sales | 113000
Marketing | 46000When no rows match, SUM returns NULL#
SELECT SUM(amount) AS revenue
FROM orders
WHERE amount > 1000;revenue
-------
NULLThere is nothing to add, so the answer is "unknown", not zero. In reports you usually want 0; wrap it with COALESCE:
SELECT COALESCE(SUM(amount), 0) AS revenue
FROM orders
WHERE amount > 1000;SUM also skips NULL values inside the column, so a missing value is treated as "not there" rather than as zero.
Conditional sums#
Put a CASE expression inside SUM to total only some rows while still looking at all of them. This counts Sales employees by adding 1 for each:
SELECT SUM(CASE WHEN department = 'Sales' THEN 1 ELSE 0 END) AS sales_people
FROM employees;sales_people
------------
2The same idea builds side-by-side totals: SUM(CASE WHEN region = 'North' THEN revenue ELSE 0 END) AS north, SUM(CASE WHEN region = 'South' THEN revenue ELSE 0 END) AS south.
Common mistakes#
Practice#
Practice exercise
Using products (name, category, price, stock), calculate the total stock value per category (price × stock), highest first.
Show hint
SUM(price * stock) with GROUP BY category, then ORDER BY the alias descending.
Show solution
SELECT category, SUM(price * stock) AS stock_value
FROM products
GROUP BY category
ORDER BY stock_value DESC;category | stock_value
------------+------------
Electronics | 760000
Furniture | 78500
Stationery | 30000Electronics is dominated by 12 laptops at 55,000 each (660,000). The Monitor has 0 stock, so it contributes nothing.
Key takeaway#
Finished this lesson?