SQL SUM
SUM adds up the values of a numeric column. It ignores NULLs and returns NULL if there are no rows to add.
SUM works on expressions too, which is how you calculate revenue: SUM(quantity * unit_price).
Syntax
SELECT SUM(column) FROM table_name;
Try it yourself
Run the example below on a real PostgreSQL database, then change it and run it again. Nothing to install, no sign-up.
sum.sql · PostgreSQL
Loading editor…
Examples
1. Total stock
SELECT SUM(stock) FROM products;
All units in stock.
2. Revenue
SELECT SUM(quantity * unit_price) AS revenue FROM order_items;
Total value of all order lines.
Common mistakes
- Summing after a join that duplicates rows, which inflates totals.
Practice: test yourself
This challenge is from our interactive course. Write the query and press Check answer.
Challenge · 10 pts
What is the total number of units in stock across all products?
challenge.sql · PostgreSQL
Loading editor…
FAQ
How do I get 0 instead of NULL?
Wrap it: COALESCE(SUM(column), 0).
Learn SQL step by step
65 hands-on exercises, streaks, a leaderboard and a certificate.