0

I have a fun issue in postgresql.

select sum(value1) as v1,
   sum(value2) as v2,
   sum(value3) as v3,
   sum(value4) as v4,
   sum(value5) as v5,
   ...
from (select * from test limit 0)x;

result:

  v1 |  v2 |  v3 |  v4 |  v5 |  ...
-----+-----+-----+-----+-----+--...
     |     |     |     |     |  ...
(1 row)

Expected: (0 row).

Truth: (1 row).

I don't want to get empty rows. How can I get correct results for this case. Thanks.

3
  • The query will always return an empty row because limit 0 means "no rows at all". So if you don't want that, then why are you using limit 0 at all? The query makes no sense Commented Apr 1, 2016 at 9:55
  • I mean results for my query have some empty rows by using sum. Above query is a case to reproduct this issue, and we sure nothing to sum here. Commented Apr 1, 2016 at 10:10
  • the expected for above query is 0 rows, not 1 row. Commented Apr 1, 2016 at 10:13

1 Answer 1

1

You can use a having clause to filter out null values:

select sum(id) 
from ( 
   select * 
   from test limit 0
) x
having sum(id) is not null;
Sign up to request clarification or add additional context in comments.

3 Comments

Thank for your help. I'm using this clause, but I hope have some ways are better, because I have 20+ sum clause on select, and I have to 20+ for having.
@ThịnhNguyễnThái: you should have included that important bit of information in your question. Broadening the question after you have received an answer is not nice
Yes, I noted. Thank you very much!

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.