Search code examples
sqlpostgresqlsubqueryaggregate-functions

PostgreSQL how to group results so all rows must be true?


In PostgreSQL, I have a query that can return 1 or more rows of boolean. How can I run a select query against this result set to get a single boolean that returns true if all of the rows are true? It returns false if one or more rows in this result set is false.


Solution

  • You are describing boolean aggregation, for which Postgres offers built-in functions such as bool_or() and bool_and():

    select bool_and(mybool) as myresult
    from (
      --- your query, that returns a boolean column called "mybool"
    ) t