SQL SUM Tutorial

The SUM command is used to sum values in a given result set. It is frequently used with the GROUP BY command.

Example 1 (no aggregation)

-- Works in PostgreSQL, MySQL, SQL Server, and Oracle SELECT SUM(dollar_amount) as sum_of_payments FROM rent_payments;

rent_payments table

id tenant_id payment_date dollar_amount
1 1 3/1/2018 2000
2 2 3/2/2018 1500
3 3 3/1/2018 1800
4 4 3/3/2018 1900
5 1 4/2/2018 2000
6 4 4/2/2018 1900

Query results

sum_of_payments
11100

Example 2 (with aggregation)

-- Works in PostgreSQL, MySQL, SQL Server, and Oracle SELECT tenant_id, SUM(dollar_amount) as sum_of_payments FROM rent_payments GROUP BY tenant_id;

rent_payments table

id tenant_id payment_date dollar_amount
1 1 3/1/2018 2000
2 2 3/2/2018 1500
3 3 3/1/2018 1800
4 4 3/3/2018 1900
5 1 4/2/2018 2000
6 4 4/2/2018 1900

Query results

tenant_id sum_of_payments
1 4000
2 1500
3 1800
4 3800

Explanation

We are finding the sum of the dollar_amount values for each unique value of the tenant_id column.