Cloud

bool_and

The bool_and() window function evaluates whether all values within a specified window of rows are TRUE.

Syntax

The syntax for this function is:

BOOL_AND (expression) OVER (
    [PARTITION BY partition_expression]
    ORDER BY sort_expression
)

Parameters

  • expression: Column or expression that the function operates on. It should evaluate to a boolean value (TRUE or FALSE).

Examples

This example uses a simplified version of the film table from the Pagila database, containing only the title, length and rating columns. The complete schema for the film table can be found on the Pagila database website.

DROP TABLE IF EXISTS film;
CREATE TABLE film (
  title text NOT NULL,
  length int,
  rating text
);
INSERT INTO film(title, length, rating) VALUES
  ('ATTRACTION NEWTON', 83, 'PG-13'),
  ('CHRISTMAS MOONSHINE', 150, 'NC-17'),
  ('DANGEROUS UPTOWN', 121, 'PG'),
  ('KILL BROTHERHOOD', 54, 'G'),
  ('HALLOWEEN NUTS', 47, 'PG-13'),
  ('HOURS RAGE', 122, 'NC-17'),
  ('PIANIST OUTFIELD', 136, 'NC-17'),
  ('PICKUP DRIVING', 77, 'G'),
  ('INDEPENDENCE HOTEL', 157, 'NC-17'),
  ('PRIVATE DROP', 106, 'PG'),
  ('SAINTS BRIDE', 125, 'G'),
  ('FOREVER CANDIDATE', 131, 'NC-17'),
  ('MILLION ACE', 142, 'PG-13'),
  ('SLEEPY JAPANESE', 137, 'PG'),
  ('WRATH MILE', 176, 'NC-17'),
  ('YOUTH KICK', 179, 'NC-17'),
  ('CLOCKWORK PARADISE', 143, 'PG-13');

This query uses the bool_and() function to evaluate if all films in each rating category have a length greater than 100:

SELECT
   title,
   length,
   rating,
   BOOL_AND(length > 100) OVER (PARTITION BY rating) as ALLlongFilmsByRating
FROM film
ORDER BY rating;

The query returns:

        title        | length | rating | alllongfilmsbyrating
---------------------+--------+--------+----------------------
 KILL BROTHERHOOD    |     54 | G      | f
 PICKUP DRIVING      |     77 | G      | f
 SAINTS BRIDE        |    125 | G      | f
 CHRISTMAS MOONSHINE |    150 | NC-17  | t
 HOURS RAGE          |    122 | NC-17  | t
 PIANIST OUTFIELD    |    136 | NC-17  | t
 INDEPENDENCE HOTEL  |    157 | NC-17  | t
 FOREVER CANDIDATE   |    131 | NC-17  | t
 WRATH MILE          |    176 | NC-17  | t
 YOUTH KICK          |    179 | NC-17  | t
 DANGEROUS UPTOWN    |    121 | PG     | t
 PRIVATE DROP        |    106 | PG     | t
 SLEEPY JAPANESE     |    137 | PG     | t
 ATTRACTION NEWTON   |     83 | PG-13  | f
 HALLOWEEN NUTS      |     47 | PG-13  | f
 MILLION ACE         |    142 | PG-13  | f
 CLOCKWORK PARADISE  |    143 | PG-13  | f
(17 rows)