Last Updated : 15 Jul, 2025
The SUM() function in PostgreSQL is used to calculate the sum of values in a numeric column. This article will guide you through the syntax, important considerations, and practical examples of using the SUM() function in PostgreSQL.
SyntaxSUM(column)
The following points need to be kept in mind while using the above function:
For example, we will be using the sample database (ie, dvdrental).
Example 1: Calculating Total Amount Paid by Each CustomerIn this example, we will calculate the total amount paid by each customer using the SUM() function combined with the GROUP BY clause.
Query:
SELECT customer_id, SUM (amount) AS total FROM payment GROUP BY customer_id;
Output:
Explanation: The output will display the 'customer_id' and the total amount paid by each customer.
Example 2: Top 10 Customers Who Paid the MostIn this example we will query for the top 10 customers who paid the most as follows.
Query:
SELECT customer_id, SUM (amount) AS total FROM payment GROUP BY customer_id ORDER BY total DESC LIMIT 10;
Output:
Explanation: The output will display the 'customer_id' and the total amount paid by the top 10 customers.
Important Points About PostgreSQL SUM() Function
- The SUM() function automatically ignores NULL values in the calculation, which ensures that the sum is accurate based on non-null entries.
- When using the SUM() function on columns with decimal values, the result retains the precision of the column type, ensuring accurate summation of financial or other precise data.
- If the SUM() function is used with a SELECT clause and there are no matching rows, it returns NULL instead of zero.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4