74

I would like to know if there's a way to compute the sum of multiple columns in PostgreSQL.

I have a table with more than 80 columns and I have to write a query that adds each value from each column.

I tried with SUM(col1, col2, col3 etc) but it didn't work.

3
  • 2
    You mean a sum per row, or a total sum for all rows? Commented Mar 30, 2013 at 15:38
  • I mean a sum per row. Commented Mar 30, 2013 at 16:29
  • 3
    I just want to clarify further that you did not mean "I want to sum all of column A and then add it to the sum of column B", you meant "In each row, I want to sum the value in column A and the value in column B and store it in the result". Commented Sep 29, 2016 at 1:48

4 Answers 4

120
SELECT COALESCE(col1,0) + COALESCE(col2,0)
FROM yourtable
Sign up to request clarification or add additional context in comments.

6 Comments

I tried that, but there are columns where there are no values (NULL) and the final result is NULL, so its not ok.
Answer modified to account for that, and the comment that you're looking for a per-row sum.
how do I do that with temporary columns that I requested with "AS" ?
@qqx Can someone explain why we need to use COALESCE here if col1 and col2 are both numeric data types?
@Bulrush that would be a separate question, and likely one that's already answered.
|
81

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=# 

1 Comment

Thanks for the comprehensive answer. Like the comments in the other answer, I was having trouble with SUM returning NULL so here's a fix if anyone needs: SELECT GREATEST(0, SUM(a + b)) FROM yourtable;
21

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

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

Comments

0
SELECT(
    SELECT SUM(t.f)
    FROM (VALUES (yourtable.col1), (yourtable.col2), (yourtable.col3)) t(f)
)
FROM yourtable;

1 Comment

Can you explain how this works? What would you call t(f)?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.