Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect NULL rows in PostgreSQL sum()

I want to aggregate the sum of a column, while tracking the presence of NULL values which signal an error condition. E.g., take the table numbers:

# select * from numbers;
  n   |  l  
------+-----
    1 | foo
    2 | foo
 NULL | bar
    4 | bar

Given a label l, I want to compute the sum of numbers n with that label, provided there are no NULL values. Ideally, for a label without any rows, the sum would be 0. So I'm looking for some query q such that q('foo') = 3, q('baz') = 0 and q('bar') somehow signals an error, e.g. by returning NULL.

I started with the sum() aggregate function, but that converts NULL rows to 0. One solution would be a variant that returns NULL provided there are any NULL values.

sum() gives

# select sum(n) from numbers where l = 'bar';
 sum 
-----
   4

but I'd rather have sumnull() with

# select sumnull(n) from numbers where l = 'bar';
 sumnull 
---------
  NULL

The best solution I've found so far is to also count non-NULL rows and compare to the total count:

# select sum(n), count(*), count(n) as notnull from numbers;
 sum | count | notnull 
-----+-------+---------
   7 |     4 |       3

Then if count is unequal to notnull, I know the result is not valid.

like image 632
robx Avatar asked Sep 26 '16 13:09

robx


People also ask

How do I get NULL records in PostgreSQL?

Example - With SELECT Statement Let's look at an example of how to use PostgreSQL IS NULL in a SELECT statement: SELECT * FROM employees WHERE first_number IS NULL; This PostgreSQL IS NULL example will return all records from the employees table where the first_name contains a NULL value.

Does SQL sum return NULL?

If there are no rows, sum() will return null . It will also return null if all rows have a null balance.

How do I get the sum of a row in PostgreSQL?

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 check if PostgreSQL is empty?

If you just need to check only empty values, then try this -> where length(stringexpression) = 0; . This works for me. I like this solution, just note that is some cases calculating exact length may be relatively expensive operation. In postgres, length(NULL) > 0 return NULL , not False .


1 Answers

1) Use COALESCE

SELECT SUM(COALESCE(n,'NaN'::numeric)) FROM numbers;

If any row is NULL then result will be as 'NaN'

2) You will get NULL as result if any row has NULL value else result as number

SELECT 
    CASE WHEN (SELECT COUNT(*) FROM numbers WHERE n IS NULL) > 0 THEN NULL
        ELSE (SELECT SUM(COALESCE(n, 0)) FROM numbers)
END
like image 193
Maxim Avatar answered Oct 10 '22 00:10

Maxim