Question

I have a query like this to group by one column and check if any of the records have data in a different column:

SELECT
  bar,
  MAX(CASE WHEN baz IS NOT NULL THEN 1 ELSE 0 END)::BOOLEAN as baz_has_data
FROM
  foos
GROUP BY
  bar

I feel like that's a little bit cryptic, and thought using ANY and ARRAY_AGG would be clearer. Unfortunately I can't find any examples that include both an IS NOT NULL and an ANY(ARRAY_AGG ...). Is this possible?

Was it helpful?

Solution

There is a dedicated aggregate function for that: bool_or():

SELECT bar, bool_or(baz IS NOT NULL) AS baz_has_data
FROM   foos
GROUP  BY 1;

Yields TRUE if at least one row in the group has a non-null value.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top