What is SUM function in SQL?
The SQL SUM is an aggregate function that is used to return the sum of a numeric column for all the values or DISTINCT values.
If null values are found in the given numeric column, these are ignored by SUM function.
The SUM function example with Select
For the example, have a look at the table in the graphic below. The tbl_emp_salary_paid stores the salaries paid to each employee every month (for the demo only).
By using the SUM function, we will get the total amount paid to all employees without using where clause.
Query:
1
2
3

SELECT SUM(emp_sal_paid) As Total_Paid
FROM tbl_emp_salary_paid

The example of using COUNT and SUM functions together
What if you want to know the count of rows for what the sum is calculated. For example, in our employee salaries table, we want to know the number of times salary paid along with sum. The query and the result are as follows from the demo table:
1
2
3
4
5

SELECT SUM(emp_sal_paid) As Total_Salary, COUNT(*) As Salaries_Count
FROM tbl_emp_salary_paid
where emp_sal_paid > 3500

Using SUM with DISTINCT clause
As mentioned in the introductory part, you may get the sum of distinct values by using the SUM function. The following query shows how to use the DISTINCT clause with SUM SQL function for that:
1
2
3

SELECT SUM(DISTINCT emp_sal_paid) AS "Unique Salary Sum"
from tbl_emp_salary_paid

The example of using Group by clause with SUM function
What about getting the sum of salaries paid to each employee separately rather than the accumulative sum of the complete column?
The answer for this is using the Group by clause with SUM function. See the following query and resultant table graphic:
1
2
3
4
5

SELECT emp_name As "Employee Name", SUM(emp_sal_paid) As "Total Sal Paid"
FROM tbl_emp_salary_paid
Group By emp_name
