PostgreSQL – SUM FUNCTION

The SUM function in PostgreSQL is used to return the sum of values. Here’s the syntax to return the sum of values in a column:

SELECT SUM(column_name) FROM table_name;

where column_name is the name of the column you want to sum and table_name is the name of the table containing the column.

For example, consider a table named sales with columns id, product_name, and price. To find the total revenue from all sales, you can use the SUM function on the price column as shown below:

SELECT SUM(price) FROM sales;

This will return the total sum of all the prices in the price column.

The SUM function only works with numeric data types, such as integer, decimal, float, and numeric. You’ll get an error if you try to use it with a non-numeric data types.

You can use the GROUP BY clause to sum the values of a column for each group of values in another column.

Example: Below sql query returns sum of values per category.

SELECT category, SUM(price) FROM sales GROUP BY category;

Similar Posts