PostgreSQL SUM
The SUM()
function calculates the total of numeric values in a specified column. It’s often combined with GROUP BY
to get subtotals.
Key Topics
1. Basic Syntax
Compute the total for a column:
SELECT SUM(salary) AS total_salary
FROM employees;
2. Using GROUP BY
Calculate totals per group (e.g., department):
SELECT department, SUM(salary) AS dept_total
FROM employees
GROUP BY department;
Each department’s salary sum is shown separately.
Best Practices
- Ensure the column is a numeric type suitable for summation (e.g., INT, DECIMAL).
- Use
GROUP BY
for aggregated sums by categories.
Key Takeaways
SUM()
returns the total of numeric values.- Combine with
GROUP BY
to compute category-wise totals.