In SQL, the aggregate function SUM()
adds a set of numbers (either in a given column or returned by some expression) and returns the summation value. It can be used in different ways. We can use it with multiple clauses, expressions, and numbers.
The syntax of the SUM()
function is as follows:
SELECT SUM(expression) FROM table_name;
This function receives only one parameter:
expression
: It could be a set of column values or a mathematical expression.This function returns the summation value.
Consider the following table for upcoming examples:
ID | Name | Gender | City | Salary |
1 | Ali | Male | Lahore | 50000 |
2 | Basit | Male | Okara | 55000 |
3 | Sana | Female | Lahore | 70000 |
4 | Dua | Female | Lahore | 60000 |
5 | Raza | Male | Karachi | 65000 |
6 | Saba | Female | Karachi | 63000 |
7 | Riaz | Male | Lahore | 60000 |
SUM()
with one columnIf we want to sum the Salary
column, we can write the query as follow:
SELECT SUM(Salary) AS total_salary FROM Persons;
SUM()
with the WHERE
clauseIf we want to sum the salary of people of Lahore
city, we can write the query as follow:
SELECT SUM(Salary) AS lahore_salaryFROM PersonsWHERE City='Lahore';
SUM()
with the GROUP BY
clauseIf we want to sum the salary of each city, we can write the query as follow:
SELECT City, SUM(Salary) AS total_salaryFROM PersonsGROUP BY City;
SUM()
with a mathematical expressionIn the SUM()
function, we can perform mathematical operations with the returned values of a column. For example, the following query will half the summation value of the Salary
column:
SELECT SUM(Salary/2) AS half_of_total_salary FROM Persons;
Suppose we pass a numeric value, i.e., 2, -5, etc., or an expression that results in a numeric value, i.e., 5+3, 1/2, etc., the SUM()
function will multiply the numeric values with the number of rows returned by the rest of the query.
SELECT SUM(2) AS double_of_total FROM Persons;SELECT SUM(1/2) AS half_of_total FROM Persons;SELECT SUM(1) AS total_number_of_males FROM Persons WHERE Gender='Male';SELECT SUM(1) AS total_number_of_taxables FROM Persons WHERE Salary >= 60000;
Line 1: The first query returns the number of rows multiplied by 2
. The SUM(2)
function returns 14
.
Line 2: This query returns the number of rows multiplied by 1/2
. The SUM(1/2)
function returns 3.5000
.
Line 4: The SUM(1)
multiplies the number of rows returned by the WHERE
clause with 1
and returns the results. This query returns the number of males in the Person
table. The output is 4
.
Line 5: In this query, SUM(1)
returns the number of employees having a salary more or equal to 60000
. The result is 5
.
Free Resources