PostgreSQL provides with a SUM() function that is used to get the addition of values of a numeric column.
The following points needs to be kept in mind while using the above function:
- It ignores all NULL values.
- If used with DISTINCT operator as SUM(DISTINCT column), it skips duplicate values.
- Using SUM() function with SELECT clause returns NULL instead of Zero.
In this example we will calculate the total amount paid by each customer using the SUM() function and GROUP BY clause as follows:
SELECT customer_id, SUM (amount) AS total FROM payment GROUP BY customer_id;
In this example we will query for the top 10 customers who paid the most as follows:
SELECT customer_id, SUM (amount) AS total FROM payment GROUP BY customer_id ORDER BY total DESC LIMIT 10;