How to use SUM() in SQL
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.
Syntax
The syntax of the SUM() function is as follows:
SELECT SUM(expression) FROM table_name;
Parameter(s)
This function receives only one parameter:
expression: It could be a set of column values or a mathematical expression.
Return value(s)
This function returns the summation value.
Examples
Consider the following table for upcoming examples:
Persons
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 |
Example 1: Using SUM() with one column
If we want to sum the Salary column, we can write the query as follow:
SELECT SUM(Salary) AS total_salary FROM Persons;
Example 2: Using SUM() with the WHERE clause
If 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';
Example 3: Using SUM() with the GROUP BY clause
If 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;
Example 4: Using SUM() with a mathematical expression
In 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;
Explanation
-
Line 1: The first query returns the number of rows multiplied by
2. TheSUM(2)function returns14. -
Line 2: This query returns the number of rows multiplied by
1/2. TheSUM(1/2)function returns3.5000. -
Line 4: The
SUM(1)multiplies the number of rows returned by theWHEREclause with1and returns the results. This query returns the number of males in thePersontable. The output is4. -
Line 5: In this query,
SUM(1)returns the number of employees having a salary more or equal to60000. The result is5.
Free Resources