6

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?

1 Answer 1

10

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.