Skip to main content

SQL SUM Function

Introduction

The SUM function is one of the most commonly used aggregate functions in SQL. It allows you to calculate the total of all values in a specified column. This function is particularly useful when you need to find totals for numerical data like sales figures, inventory counts, or any other quantitative information stored in your database.

In this tutorial, you'll learn:

  • What the SUM function is and why it's useful
  • The basic syntax of the SUM function
  • How to use SUM with GROUP BY
  • How to handle NULL values
  • Practical examples in real-world scenarios

Basic Syntax

The basic syntax of the SUM function is:

sql
SELECT SUM(column_name) FROM table_name;

Where:

  • SUM() is the function name
  • column_name is the name of the column containing the values you want to add
  • table_name is the name of the table containing the column

Simple SUM Example

Let's start with a basic example. Imagine we have a table called sales with the following data:

sale_idproduct_nameamount
1Laptop1200
2Keyboard85
3Mouse25
4Monitor350
5Headphones150

To calculate the total amount of all sales, we would use:

sql
SELECT SUM(amount) AS total_sales 
FROM sales;

Output:

total_sales
-----------
1810

The query returns the sum of all values in the amount column (1200 + 85 + 25 + 350 + 150 = 1810).

Using SUM with GROUP BY

The SUM function becomes even more powerful when combined with the GROUP BY clause. This allows you to calculate sums for different groups of data.

Let's expand our example with a more detailed sales table:

sale_idproduct_namecategoryamountsale_date
1LaptopElectronics12002023-01-15
2KeyboardAccessories852023-01-20
3MouseAccessories252023-01-25
4MonitorElectronics3502023-02-05
5HeadphonesAccessories1502023-02-10
6LaptopElectronics13002023-02-15
7PrinterElectronics2752023-03-01

To get the total sales amount for each product category:

sql
SELECT 
category,
SUM(amount) AS category_total
FROM
sales
GROUP BY
category;

Output:

category     | category_total
-------------|---------------
Electronics | 3125
Accessories | 260

Using SUM with WHERE Clause

You can also use the SUM function with the WHERE clause to calculate the sum of specific rows:

sql
SELECT 
SUM(amount) AS february_sales
FROM
sales
WHERE
sale_date BETWEEN '2023-02-01' AND '2023-02-28';

Output:

february_sales
--------------
1800

This query calculates the sum of sales amounts for the month of February only.

Handling NULL Values

The SUM function automatically ignores NULL values. Let's see an example with a table that contains some NULL values:

sale_idproduct_nameamount
1Laptop1200
2Keyboard85
3MouseNULL
4Monitor350
5HeadphonesNULL
sql
SELECT SUM(amount) AS total_sales 
FROM sales;

Output:

total_sales
-----------
1635

The SUM function only adds the non-NULL values (1200 + 85 + 350 = 1635).

SUM with HAVING Clause

You can use the SUM function in a HAVING clause to filter groups based on aggregate values:

sql
SELECT 
category,
SUM(amount) AS category_total
FROM
sales
GROUP BY
category
HAVING
SUM(amount) > 1000;

Output:

category     | category_total
-------------|---------------
Electronics | 3125

This query returns only categories where the total sales amount exceeds 1000.

Combining SUM with Other Aggregate Functions

SUM can be used alongside other aggregate functions to provide a more comprehensive analysis:

sql
SELECT 
category,
SUM(amount) AS total_amount,
AVG(amount) AS average_amount,
COUNT(*) AS number_of_sales,
MAX(amount) AS highest_sale,
MIN(amount) AS lowest_sale
FROM
sales
GROUP BY
category;

Output:

category     | total_amount | average_amount | number_of_sales | highest_sale | lowest_sale
-------------|--------------|----------------|-----------------|--------------|-------------
Electronics | 3125 | 781.25 | 4 | 1300 | 275
Accessories | 260 | 86.67 | 3 | 150 | 25

Real-World Applications

Example 1: Monthly Sales Report

sql
SELECT 
EXTRACT(MONTH FROM sale_date) AS month,
EXTRACT(YEAR FROM sale_date) AS year,
SUM(amount) AS monthly_total
FROM
sales
GROUP BY
EXTRACT(YEAR FROM sale_date),
EXTRACT(MONTH FROM sale_date)
ORDER BY
year, month;

Output:

month | year | monthly_total
------|------|---------------
1 | 2023 | 1310
2 | 2023 | 1800
3 | 2023 | 275

Example 2: Product Performance Analysis

sql
SELECT 
product_name,
COUNT(*) AS times_sold,
SUM(amount) AS total_revenue
FROM
sales
GROUP BY
product_name
ORDER BY
total_revenue DESC;

Output:

product_name | times_sold | total_revenue
-------------|------------|---------------
Laptop | 2 | 2500
Monitor | 1 | 350
Printer | 1 | 275
Headphones | 1 | 150
Keyboard | 1 | 85
Mouse | 1 | 25

Example 3: Running Total

Some database systems allow you to create running totals using window functions along with SUM:

sql
SELECT 
sale_id,
sale_date,
product_name,
amount,
SUM(amount) OVER (ORDER BY sale_date) AS running_total
FROM
sales
ORDER BY
sale_date;

Output:

sale_id | sale_date  | product_name | amount | running_total
--------|------------|--------------|--------|---------------
1 | 2023-01-15 | Laptop | 1200 | 1200
2 | 2023-01-20 | Keyboard | 85 | 1285
3 | 2023-01-25 | Mouse | 25 | 1310
4 | 2023-02-05 | Monitor | 350 | 1660
5 | 2023-02-10 | Headphones | 150 | 1810
6 | 2023-02-15 | Laptop | 1300 | 3110
7 | 2023-03-01 | Printer | 275 | 3385

Common Errors and Troubleshooting

1. Mixing Aggregated and Non-Aggregated Columns

One common error is trying to select both aggregated and non-aggregated columns without a GROUP BY clause:

sql
-- This will cause an error
SELECT product_name, SUM(amount)
FROM sales;

Solution: Use GROUP BY for non-aggregated columns:

sql
SELECT product_name, SUM(amount) 
FROM sales
GROUP BY product_name;

2. SUM on Non-Numeric Data

Another common error is trying to use SUM on non-numeric columns:

sql
-- This will cause an error
SELECT SUM(product_name)
FROM sales;

Solution: Ensure you're only using SUM with numeric data types.

Summary

The SQL SUM function is a powerful tool for calculating totals in your data analysis workflows. Key points to remember:

  • SUM calculates the total of values in a specified column
  • It automatically ignores NULL values
  • It works well with GROUP BY to calculate totals for different groups
  • It can be combined with WHERE to filter rows before summing
  • It can be used in HAVING clauses to filter groups based on sum values
  • It's commonly used with other aggregate functions for comprehensive analysis

With practice, you'll find the SUM function indispensable for generating reports, analyzing data patterns, and making data-driven decisions in your applications.

Practice Exercises

  1. Create a table of monthly sales and calculate the total for the entire year.
  2. Calculate the sum of sales for each product category and identify which category contributes the most to total revenue.
  3. Find the total sales amount for each day of the week to identify sales patterns.
  4. Calculate running totals by date to track cumulative sales progress.
  5. Combine SUM with conditional logic (CASE statements) to calculate sales totals for different price ranges.

Additional Resources



If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)