Sub topic 6
Boolean Values and NULL
This chapter assumes you know SELECT, INSERT, CREATE TABLE, and basic constraints. It also assumes you can run queries in psql or another PostgreSQL client.
Boolean values
A Boolean is a type with two ordinary values: TRUE and FALSE. PostgreSQL also supports NULL, which means that the value is missing or unknown. NULL is not the same as FALSE.
Use Boolean columns for facts that have two clear states:
CREATE TABLE feature_flags (
user_id bigint PRIMARY KEY,
email_enabled boolean NOT NULL DEFAULT true,
sms_enabled boolean NOT NULL DEFAULT false
);
INSERT INTO feature_flags (user_id, email_enabled)
VALUES (101, true);
SELECT user_id
FROM feature_flags
WHERE email_enabled;PostgreSQL accepts Boolean literals such as TRUE and FALSE. In a WHERE clause, a Boolean column can be used directly. The query above returns rows where email_enabled is true.
| Expression | Result |
|---|---|
| `TRUE AND FALSE` | `FALSE` |
| `TRUE OR FALSE` | `TRUE` |
| `NOT TRUE` | `FALSE` |
| `TRUE AND NULL` | `NULL` |
NULL and three-valued logic
SQL uses three logical results: true, false, and unknown. An expression involving a missing value often produces NULL, representing unknown.
SELECT
TRUE AND NULL AS true_and_unknown,
FALSE AND NULL AS false_and_unknown,
TRUE OR NULL AS true_or_unknown,
NOT NULL AS not_unknown;A WHERE clause keeps only rows where its condition is TRUE. It removes rows where the condition is FALSE or NULL.
For example, this condition does not find missing values:
SELECT *
FROM feature_flags
WHERE email_enabled = NULL;The comparison result is unknown, even when email_enabled is null. Use IS NULL or IS NOT NULL instead:
SELECT *
FROM feature_flags
WHERE email_enabled IS NULL;You can also use IS TRUE and IS FALSE when you want to test the logical state explicitly. IS NOT TRUE matches both false and unknown values.
Constraints and defaults
A default fills in a value only when an INSERT omits the column. It does not replace an explicitly supplied NULL.
CREATE TABLE tasks (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
description text NOT NULL,
completed boolean NOT NULL DEFAULT false
);
INSERT INTO tasks (description)
VALUES ('Back up the database');The row receives completed = false. An attempt to insert NULL into completed fails because of NOT NULL.
A CHECK constraint passes when its expression is true or unknown. Therefore, combine CHECK with NOT NULL when missing values are invalid.
CREATE TABLE accounts (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
active boolean NOT NULL DEFAULT true,
balance numeric NOT NULL CHECK (balance >= 0)
);Null-safe comparisons
Use IS DISTINCT FROM when two values should compare as different if exactly one is null. Use IS NOT DISTINCT FROM when two nulls should count as equal.
Exercise
Write a query that returns tasks that are either incomplete or have an unknown completion value.
Show answer
SELECT * FROM tasks WHERE completed IS NOT TRUE;