SQL Sum

The SUM function adds together all the numeric values in a column and returns a single total.

Adding up a column

SUM() is used whenever you need a total: the combined salary of every employee, total sales for a month, or the sum of hours logged. It only works on numeric data, and it ignores any NULL values it encounters rather than treating them as zero.

Total payroll

SELECT SUM(salary) AS total_payroll
FROM Employees;
Note: If no rows match the query, SUM returns NULL, not 0. Wrap it in COALESCE(SUM(salary), 0) when you would rather show a zero.

Summing an expression

The value inside SUM() does not have to be a plain column. You can sum the result of a calculation, which lets you total derived amounts such as annual pay computed from a monthly figure.

Sum of a calculated value

SELECT SUM(salary * 12) AS total_annual_pay
FROM Employees;

Totals per group

With GROUP BY you can produce a separate total for each category. The query below gives the combined salary budget of each department in one result set.

Salary budget by department

SELECT department, SUM(salary) AS salary_budget
FROM Employees
GROUP BY department;
  • SUM only accepts numeric columns or numeric expressions.
  • NULL values are skipped during the calculation.
  • Use SUM(DISTINCT column) to total only the unique values.
  • Combine SUM with GROUP BY for per-category totals.
Note: Do not confuse SUM with COUNT. SUM adds the values stored in a column, while COUNT simply tallies how many rows there are.