Since PostgreSQL 9.4 contains a FILTER article , which allows a very concise query to calculate true values:
select count(*) filter (where myCol) from tbl;
The above query is a bad example that a simple WHERE clause will suffice and is intended only to demonstrate syntax. Where the FILTER condition is shining is that it easily combines with other units:
select count(*), -- all count(myCol), -- non null count(*) filter (where myCol) -- true from tbl;
The proposal is especially convenient for aggregates in a column that uses another column as a predicate, while allowing you to get only filtered aggregates in one query:
select count(*), sum(otherCol) filter (where myCol) from tbl;
Ilja Everilä May 19 '16 at 9:28 pm 2016-05-19 21:28
source share