Sub topic 6
Boolean values and NULL
This chapter assumes you can write basic SELECT, INSERT and CREATE TABLE statements and run queries in psql. It covers the boolean type, why a boolean column can hold three states, and the errors that follow from that.
The boolean type
boolean stores one of three values: true, false, or NULL. It uses one byte per value. The standard literals are TRUE and FALSE. PostgreSQL also accepts these spellings in quoted strings and casts them to boolean:
| True values | False values |
|---|---|
| `'true'`, `'t'` | `'false'`, `'f'` |
| `'yes'`, `'y'` | `'no'`, `'n'` |
| `'on'`, `'1'` | `'off'`, `'0'` |
Matching is case-insensitive and ignores surrounding whitespace. Any other string raises an error. psql displays booleans as t and f, and an empty cell for NULL.
SELECT 'yes'::boolean AS a,
'F'::boolean AS b,
'1'::boolean AS c;Output: t, f, t.
SELECT 'maybe'::boolean;
-- ERROR: invalid input syntax for type boolean: "maybe"Integers do not convert implicitly to boolean. WHERE 1 fails with an error saying the argument of WHERE must be type boolean. You can cast explicitly: 1::boolean is true, and 0::boolean is false.
NULL means unknown
NULL is not a value of any type. It marks a missing or unknown value. Most operators return NULL when any input is NULL, because the true answer cannot be known.
SELECT NULL = NULL AS equal,
NULL <> 1 AS not_equal,
NULL + 5 AS arithmetic,
NULL IS NULL AS is_null;The first three columns are NULL. Only the last is true. To test for NULL, use IS NULL or IS NOT NULL. Writing col = NULL is a common bug. It is never true, so it matches no rows.
Three-valued logic
Boolean expressions in SQL can evaluate to true, false or NULL. The NULL result is called "unknown". The logical operators follow these tables.
| a | b | a AND b | a OR b |
|---|---|---|---|
| true | NULL | NULL | true |
| false | NULL | false | NULL |
| NULL | NULL | NULL | NULL |
NOT NULL evaluates to NULL.
The rule behind the table is simple. AND is false if either side is definitely false, because no value for the unknown side can change the result. OR is true if either side is definitely true, for the same reason. Otherwise the result is unknown.
How WHERE and CHECK treat NULL
WHERE keeps a row only when the condition is true. Rows where the condition is false or NULL are dropped. CHECK constraints behave differently. A row passes a CHECK unless the condition is false, so a NULL result passes.
CREATE TABLE accounts (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
is_active boolean,
balance numeric(12,2) CHECK (balance >= 0)
);
INSERT INTO accounts (is_active, balance) VALUES
(true, 10),
(false, 20),
(NULL, NULL); -- passes the CHECK because NULL >= 0 is NULL
SELECT count(*) FROM accounts WHERE is_active; -- 1
SELECT count(*) FROM accounts WHERE NOT is_active; -- 1
SELECT count(*) FROM accounts WHERE is_active IS NULL; -- 1The first two queries return one row each. The NULL row appears in neither, so the two counts add up to 2, not 3. This is the usual source of "missing rows" bugs with nullable booleans.
To make a CHECK reject NULL, add NOT NULL to the column. The constraint on balance above would then also guard against missing values.
Comparing safely with NULL
Two tools handle NULL in comparisons.
IS DISTINCT FROM treats NULL as an ordinary value. Two NULLs are not distinct, and a NULL differs from any non-NULL value. It always returns true or false.
SELECT 1 IS DISTINCT FROM NULL AS a, -- true
NULL IS DISTINCT FROM NULL AS b; -- falseThe IS TRUE, IS NOT TRUE, IS FALSE, IS NOT FALSE, IS UNKNOWN and IS NOT UNKNOWN tests also never return NULL. is_active IS NOT TRUE matches both false and NULL rows.
SELECT count(*) FROM accounts WHERE is_active IS NOT TRUE; -- 2COALESCE supplies a default for NULL: COALESCE(is_active, false) returns false for unknown values.
Aggregates and NULL
Aggregate functions ignore NULL inputs, with the exception of count(*), which counts rows. count(is_active) counts only non-NULL values.
SELECT count(*) AS rows, -- 3
count(is_active) AS known, -- 2
count(balance) AS with_balance -- 2
FROM accounts;PostgreSQL also provides bool_and and bool_or, which return whether all or any non-NULL inputs are true. They return NULL when there are no non-NULL inputs. Use count(*) FILTER (WHERE is_active) to count true values.
Designing boolean columns
A nullable boolean has three states, and your application must decide what the third one means. If the data has only two states, remove the third:
CREATE TABLE users (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
email text NOT NULL,
is_verified boolean NOT NULL DEFAULT false
);Keep NULL only when "not yet known" is a real state, for example consented boolean where NULL means the user has not answered.
Other guidelines:
- Name columns as statements, such as
is_paidorhas_shipped, soWHERE is_paidreads naturally. - Do not store booleans as
integer,char(1)or'Y'/'N'text. They need extra checks and give up the type's built-in operators. - If a flag may later need more than two states, such as
pending,approvedandrejected, use an enum or a lookup table rather than several booleans. - A boolean column alone makes a poor index, because it has only two values. A partial index on the rare value works better, for example
CREATE INDEX ON users (id) WHERE NOT is_verified;.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| `WHERE col = NULL` returns no rows | Comparison with `NULL` is unknown | Use `IS NULL` |
| `NOT IN (subquery)` returns nothing | One `NULL` in the list makes the result unknown | Use `NOT EXISTS`, or filter `NULL`s out |
| Rows missing from both `col` and `NOT col` | `NULL` rows match neither | Use `IS NOT TRUE` or `COALESCE` |
| `invalid input syntax for type boolean` | String is not a recognized literal | Validate input or fix the value |
Exercise
A table tasks has a nullable boolean column done. It contains 5 rows with true, 3 with false and 2 with NULL. How many rows do WHERE done, WHERE NOT done and WHERE done IS NOT TRUE return? Which expression would you use to list every task that is not finished, including those with unknown status?
Show answer
WHERE done returns 5 rows and WHERE NOT done returns 3, since NOT NULL is NULL and those rows are dropped. WHERE done IS NOT TRUE returns 5 rows (the 3 false and 2 NULL). Use WHERE done IS NOT TRUE (or WHERE NOT COALESCE(done, false)) to list all unfinished tasks.
Exercise
What does SELECT true AND NULL, false AND NULL, true OR NULL, false OR NULL; return?
Show answer
NULL, false, true, NULL. AND is false when either side is false, and OR is true when either side is true. Otherwise the unknown side makes the result NULL.