Course contentsShow
← Data Science
Lesson 883 of 2,14523. SQL Aggregation and GroupingFree lesson

SUM: Calculating Totals

Using SUM to calculate the total of numeric values, handling nulls, and understanding when to use it.

SUM: Calculating Totals

What you'll learn: How to use the SUM() aggregate function to add up numeric values across rows in SQL.

What is SUM?

SUM() is an aggregate function that calculates the total of all numeric values in a column. Think of it like a calculator automatically adding up a long column of numbers in a spreadsheet—but SQL can do this instantly across millions of rows.

Unlike COUNT() which counts rows, SUM() adds up the values themselves. This makes it perfect for questions like "What's our total revenue?" or "How many items were sold in total?"

Basic Syntax

SELECT SUM(column_name)
FROM table_name;

For example, to find total sales:

SELECT SUM(sale_amount)
FROM orders;

How SUM Handles NULLs

Important: SUM() automatically ignores NULL values. If a column has 5 rows with values [10, 20, NULL, 30, NULL], SUM() returns 60—not an error. This is usually helpful, but be aware that missing data won't break your calculation; it's simply excluded.

When to Use SUM

Use SUM() when you need to:

  • Calculate total sales, revenue, or expenses
  • Find total quantities (items sold, hours worked)
  • Add up any numeric metric across multiple rows

Don't use SUM for: Counting rows (use COUNT), averaging (use AVG), or non-numeric data (it only works with numbers).

Practical Example

SELECT SUM(quantity) AS total_items_sold
FROM order_items;

This adds up all quantities across every order item, giving you a single total.

Key Takeaway: SUM() calculates the total of numeric values in a column, automatically ignoring NULLs, and is essential for computing totals like revenue, quantities, or any cumulative numeric metric.