![]() |
VOOZH | about |
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.
SUM(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).
In 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:
👁 ImageExplanation: The output will display the 'customer_id' and the total amount paid by each customer.
In 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:
👁 ImageExplanation: The output will display the 'customer_id' and the total amount paid by the top 10 customers.
- 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.