Full answer
Setup for the example:
sql
CREATE TABLE flags (name text, active boolean);
INSERT INTO flags VALUES ('a', true), ('b', 'yes'), ('c', 'off'), ('d', '0'), ('e', NULL), ('f', 'T');sql
SELECT name, active, active IS NOT TRUE AS not_true FROM flags ORDER BY name;Result:
text
name | active | not_true
------+--------+----------
a | t | f
b | t | f
c | f | t
d | f | t
e | NULL | t
f | t | f
(6 rows)sql
SELECT count(*) FILTER (WHERE active) AS on_count, count(*) FILTER (WHERE NOT active) AS off_count, sum(active::int) AS summed, bool_and(active) AS all_on FROM flags;Output:
text
on_count | off_count | summed | all_on
----------+-----------+--------+--------
3 | 2 | 3 | f
(1 row)sql
INSERT INTO flags VALUES ('g', 'maybe');PostgreSQL returns:
text
ERROR: invalid input syntax for type boolean: "maybe"All the text forms were stored as plain true or false, shown as t and f. Row e is NULL, so IS NOT TRUE is true for it while NOT active would be NULL. The FILTER counts show three true and two false values, with the NULL in neither, and bool_and ignores NULLs too. An unrecognised word such as 'maybe' is rejected with an 'invalid input syntax for type boolean' error, so text flags from imports are validated on the way in.
sql
CREATE TABLE flags (name text, active boolean);
INSERT INTO flags VALUES ('a', true), ('b', 'yes'), ('c', 'off'), ('d', '0'), ('e', NULL), ('f', 'T');
SELECT name, active, active IS NOT TRUE AS not_true FROM flags ORDER BY name;
SELECT count(*) FILTER (WHERE active) AS on_count, count(*) FILTER (WHERE NOT active) AS off_count, sum(active::int) AS summed, bool_and(active) AS all_on FROM flags;
INSERT INTO flags VALUES ('g', 'maybe');Run on PostgreSQL 17.12 (Debian 17.12-0+deb13u1) in a fresh schema, twice, with identical output.
Key points
- Many text literals map to booleans
- Booleans work directly in WHERE
- FILTER counts true values
- NULL is neither true nor false
- IS NOT TRUE includes NULLs
Common mistakes
- Storing flags as 'Y'/'N' text
- Forgetting NULL in boolean logic
Follow-ups
- When would you make a boolean column NOT NULL?
- What does bool_or return over no rows?
Tips
- Mention the NULL state