Saturday, April 21, 2012

Detect if a given column has all values set to null

Given this:

create table test(
x char(1) not null,
y char(1)
);

insert into test(x,y) values
('A',null),
('A','E'),
('B', null),
('B', null);


How you would detect that if column x's y column has all values set to null? in this case, the output is B

One might right away write the code like this:

select x
from test
group by x
having sum((y is not null)::int) = count(x);


That logic is needlessly complicated to detect if a given column has all values set to null. Just use MAX


select x
from test
group by x
having max(y) is null;


UPDATE 2012-05-09

This is way much better:

select x
from test
group by x
having every(y is null)

every works only on Postgresql.

every shall stop as soon any of its element didn't satisfy the condition. It's faster than max or sum-count combo approach. every is an alias for bool_and. For MySQL, use bit_and. Postgresql's every is short-circuited

No comments:

Post a Comment