Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compute the sum of multiple columns in PostgreSQL

Tags:

postgresql

People also ask

How do I sum a column in PostgreSQL?

Summary. Use the SUM() function to calculate the sum of values. Use the DISTINCT option to calculate the sum of distinct values. Use the SUM() function with the GROUP BY clause to calculate the sum for each group.

How do I create a sum function in PostgreSQL?

PostgreSQL SUM function is used to find out the sum of a field in various records. You can take the sum of various records set using the GROUP BY clause. The following example will sum up all the records related to a single person and you will have salary for each person.


SELECT COALESCE(col1,0) + COALESCE(col2,0)
FROM yourtable

It depends on how you'd like to sum the values. If I read your question correctly, you are looking for the second SELECT from this example:

template1=# SELECT * FROM yourtable ;
 a | b 
---+---
 1 | 2
 4 | 5
(2 rows)

template1=# SELECT a + b FROM yourtable ;
 ?column? 
----------
        3
        9
(2 rows)

template1=# SELECT SUM( a ), SUM( b ) FROM yourtable ;
 sum | sum 
-----+-----
   5 |   7
(1 row)

template1=# SELECT SUM( a + b ) FROM yourtable ;
 sum 
-----
  12
(1 row)

template1=# 

Combined the current answers and used this to get total SUM:

SELECT SUM(COALESCE(col1,0) + COALESCE(col2,0)) FROM yourtable;