SQL SUM() Function
The SUM()
function in SQL is an aggregate function that calculates the total sum of a numeric column. It is commonly used with the GROUP BY
clause to get the sum for each group or without it to get the sum of all rows.
Basic Syntax
SELECT SUM(column_name) FROM table_name WHERE condition;
Examples
Example 1: Simple Sum
Consider a table Sales
with the following data:
ID | Product | Amount |
---|---|---|
1 | A | 100 |
2 | B | 200 |
3 | A | 150 |
4 | B | 300 |
5 | A | 250 |
To get the total sales amount:
SELECT SUM(Amount) AS TotalSales FROM Sales;
Output:
TotalSales |
---|
1000 |
Example 2: Sum with Condition
To get the total sales amount for product 'A':
SELECT SUM(Amount) AS TotalSalesForA FROM Sales WHERE Product = 'A';
Output:
TotalSalesForA |
---|
500 |
Example 3: Sum with Group By
To get the total sales amount for each product:
SELECT Product, SUM(Amount) AS TotalSales FROM Sales GROUP BY Product;
Output:
Product | TotalSales |
---|---|
A | 500 |
B | 500 |
Notes
- The
SUM()
function ignoresNULL
values. - It can be used in conjunction with other aggregate functions like
AVG()
,COUNT()
, etc. - It can be used in
HAVING
clauses to filter groups based on aggregate values.
Example 4: Sum with HAVING
To get the products with total sales greater than 400:
SELECT Product, SUM(Amount) AS TotalSales FROM Sales GROUP BY Product HAVING SUM(Amount) > 400;
Output:
Product | TotalSales |
---|---|
A | 500 |
B | 500 |
These examples illustrate how the SUM()
function can be used to calculate the total of a numeric column under various conditions and groupings.
At Online Learner, we're on a mission to ignite a passion for learning and empower individuals to reach their full potential. Founded by a team of dedicated educators and industry experts, our platform is designed to provide accessible and engaging educational resources for learners of all ages and backgrounds.
Copyright 2023-2025 © All rights reserved.