SQL SUM() Function
The SQL SUM()
function calculates the total sum of a numeric column. It is commonly used to aggregate data in SQL queries.
Basic Usage
The SUM()
function can be used to calculate the total sum of a column in a table.
SELECT SUM(salary) AS total_salaries FROM employees;
This query calculates the total sum of salaries in the employees
table.
Using SUM() with WHERE Clause
The SUM()
function can be used with a WHERE
clause to calculate the sum of a column for rows that match a specific condition.
SELECT SUM(salary) AS total_sales_salaries
FROM employees
WHERE department = 'Sales';
This query calculates the total sum of salaries for employees in the Sales department.
Using SUM() with GROUP BY
The SUM()
function is often used with the GROUP BY
clause to calculate the sum of a column for each group.
SELECT department, SUM(salary) AS total_salaries
FROM employees
GROUP BY department;
This query calculates the total sum of salaries for each department.
Example 1: Calculating Total Sales
SELECT SUM(sale_amount) AS total_sales
FROM sales;
This query calculates the total sum of sales in the sales
table.
Example 2: Calculating Total Sales by Product
SELECT product_id, SUM(sale_amount) AS total_sales
FROM sales
GROUP BY product_id;
This query calculates the total sum of sales for each product in the sales
table.
Example 3: Calculating Total Sales by Region
SELECT region, SUM(sale_amount) AS total_sales
FROM sales
GROUP BY region;
This query calculates the total sum of sales for each region in the sales
table.
Example 4: Using SUM() with HAVING Clause
SELECT department, SUM(salary) AS total_salaries
FROM employees
GROUP BY department
HAVING SUM(salary) > 1000000;
This query calculates the total sum of salaries for each department and only returns departments where the total sum of salaries is greater than 1,000,000.
The SUM()
function is a versatile tool for aggregating numeric data in SQL. It can be used to calculate the total sum of a column, often in combination with WHERE
, GROUP BY
, and HAVING
clauses.