SUM(): Calculate the Total
The SUM() function returns the total of all the values in a number column.
It is often used for totals in reports.
Syntax
SELECT SUM(column) FROM table_name WHERE condition;
Example 1: Total Age of All Employees
SELECT SUM(age) FROM employees;
Output:
sum
-----
570
(1 row)
This adds up the ages of all 20 employees.
Example 2: Total Age per Department
SELECT department, SUM(age) AS total_age
FROM employees
GROUP BY department
ORDER BY department;
Output:
department | total_age
------------+-----------
Finance | 123
HR | 52
IT | 168
Marketing | 59
Sales | 168
(5 rows)
This returns the total age of the employees in each department.
Tip
SUM()ignoresNULLvalues.- It works only with number columns.
SUM(name)gives an error.
In the exercise, add up the ages for each gender.