PostgreSQL BOOL_AND() Function
Summary: in this tutorial, you will learn about the PostgreSQL BOOL_AND()
function to aggregate boolean values across rows within a group.
Introduction to the PostgreSQL BOOL_AND() function
The BOOL_AND()
is an aggregate function that allows you to aggregate boolean values across rows within a group.
The following shows the syntax of the BOOL_AND()
function:
In this syntax:
expression
: This is a boolean expression to evaluate.
The BOOL_AND()
function returns true if all values in the group are true, or false otherwise.
It’s important to note that the BOOL_AND()
function ignores NULL
s within the group.
PostgreSQL BOOL_AND() function examples
Let’s explore some examples of using the BOOL_AND()
function.
1) Setting up sample tables
First, create tables called teams
and members
:
Second, insert rows into the tables:
The teams
table:
The members
table:
2) Basic BOOL_AND() function example
The following example uses the BOOL_AND()
function to test if all projects are active in the projects
table:
Output:
The BOOL_AND()
function returns true indicating that there are inactive projects in the projects
table.
2) Using BOOL_AND() function with GROUP BY clause
The following example uses the BOOL_AND()
function with the GROUP BY
clause to check if there are active projects in each team:
Output:
The output indicates that teams B and C have projects that are active (or NULL) whereas team C has inactive projects.
3) Using BOOL_AND() function in HAVING clause
The following example uses the BOOL_AND()
function with the GROUP BY
and HAVING clauses to retrieve teams that have active projects:
Output:
Summary
- Use the
BOOL_AND()
function to aggregate boolean values across rows, which returns true if all values are true or false otherwise. - The
BOOL_AND()
function ignores NULLs in the group.