SUM function is an aggregate function that allows you to get the sum of values.
Example:
Consider the employee table as shown below:
| id | first_name | last_name | department | salary |
| 101 | bryan | walker | sales | 50,000 |
| 102 | alex | carpenter | accounts | 55,000 |
| 103 | sam | white | sales | 60,000 |
| 104 | john | barry | sales | 54,000 |
| 105 | bill | wood | accounts | 65,000 |
| 106 | robert | hopkins | support | 70,000 |
| 107 | david | lee | support | 72,000 |
| 108 | jack | sears | support | 65,000 |
| 109 | tom | young | sales | 55,000 |
You can get the sum of all salaries as shown below:
SELECT SUM(salary) FROM employee; sum ------ 546,000
You can use SUM along with the group by clause. Example: To return sum of salaries per department, you can group by department as shown below:
SELECT department, SUM(salary) FROM employee GROUP BY department; department sum ---------- --- sales 219,000 accounts 120,000 support 207,000
You can filter grouped results using HAVING clause. Example: Below query returns only the departments that are paying more than 200,000 to employees.
SELECT department, SUM(salary) FROM employee GROUP BY department HAVING SUM(salary)>200000; department sum ---------- --- sales 219,000 support 207,000