AggregateSQL standard

SUM

Adds up values from many rows and returns the total.

Syntax

SUM(<expression>)
SUM(DISTINCT <expression>)

An aggregate function: it turns a group of rows into one number — the total. It skips NULL. Together with GROUP BY it calculates the total separately for each group: revenue by month, salaries by department.

Data for the examples

employees

namedepartmentsalarybonusphone
Emmabackend1200300+44 7700 900123
Liambackend1000NULLNULL
Oliviafrontend1350150+44 7700 900456
Noahfrontend950NULL+44 7700 900789
Sophiadesign1200200NULL

orders

idcreated_atamount
12026-07-03 10:15:00120.50
22026-07-28 18:40:0080.25
32026-08-09 09:05:00199.99
42026-08-21 14:30:0045.00
52026-09-02 11:00:0064.75

These tables already exist in the sandbox — the examples below use them. Want to try this in your own database? Copy the SQL.

Total revenue
SELECT SUM(amount) AS revenue
FROM orders;
revenue
510.49
The payroll of each department
SELECT department, SUM(salary) AS payroll
FROM employees
GROUP BY department
ORDER BY department;
departmentpayroll
backend2200
design1200
frontend2300
When the data has NULL
SELECT SUM(bonus) AS total_bonus,
SUM(salary + bonus) AS salary_plus_bonus,
SUM(salary) + SUM(bonus) AS sum_of_sums
FROM employees;
total_bonussalary_plus_bonussum_of_sums
65044006350

salary + bonus gives NULL for Liam and Noah, so their salaries dropped out of the second total entirely: 4400 instead of 6350.

Watch out

If there are no rows or all the values are NULL, the result is NULL, not 0. If you need a zero — COALESCE(SUM(amount), 0).

A NULL inside an expression “swallows” the whole row: SUM(salary + bonus) won't count the salary of those with no bonus. Write SUM(salary + COALESCE(bonus, 0)).

Related functions

Learn more in the course