
Sum in PostgreSql
SUM()
in PostgreSQL
The SUM()
function in PostgreSQL calculates the total sum of a numeric column.
Syntax
SELECT SUM(column_name) FROM table_name WHERE condition;
1. Summing All Values in a Column
SELECT SUM(salary) FROM employees;
✅ Returns the total salary of all employees.
2. Using SUM()
with a WHERE
Condition
SELECT SUM(salary) FROM employees WHERE department = 'IT';
✅ Returns the total salary of employees in the IT department.
3. Using SUM()
with GROUP BY
SELECT department, SUM(salary) FROM employees GROUP BY department;
✅ Returns the total salary for each department.
4. Using SUM()
with ROUND()
SELECT ROUND(SUM(salary), 2) FROM employees;
✅ Returns the total salary rounded to 2 decimal places.
5. Handling NULL
Values in SUM()
SUM()
ignores NULL values in calculations.- If all values are NULL, it returns NULL.
Example:
SELECT SUM(bonus) FROM employees;
✅ If some employees don’t have a bonus (NULL
), they are not included in the sum.