开发者

Select or boolean aggregate function in PostgreSQL

I would like to ask you how in PostgreSQL can you check if one of bo开发者_如何学编程olean values in table's column is true using select or aggregate function?


There are few boolean specific aggregate functions you may use: bool_and, bool_or, every.

In your particular case you need bool_or aggregate.
The query is as simple as this:

SELECT bool_or(my_column) FROM my_table


You can't use SUM(DATA) but you could cast the value (see below) to int (0=false, 1=true). However it may be more efficient to use EXISTS(...), specially if you are not interested in the number of TRUE values.

create table test(data boolean);
insert into test values(true), (false);
select sum(cast(data as int)) from test;
select exists(select * from test where data);


To know whether there is at least 1 true value:

select sum(cast(data as int)) > 0

This is better than the exists solution because it can be embedded into a larger query, maybe containing group by and other where clauses

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜