Three Valued Logic Is Not True
Plain boolean predicates drop NULL rows silently; IS TRUE and IS NOT TRUE make the treatment of unknown three-valued states explicit.
Code
WITH subscriptions(id, user_id, active) AS (
VALUES
(1, 10, true),
(2, 11, false),
(3, 12, NULL)
)
-- 三值逻辑(three-valued logic):true / false / NULL,三种状态都要想清楚
SELECT
id,
user_id,
active,
active = true AS eq_true, -- NULL 行得 NULL,被 WHERE 丢弃
active IS TRUE AS is_true, -- NULL 仍不算
active IS NOT TRUE AS is_not_true -- false 与 NULL 都算进来
FROM subscriptions
ORDER BY id;
-- WHERE active 等价 active = true:NULL 行永远查不出来
-- WHERE active IS TRUE 显式表达“只要明确为 true”
-- WHERE active IS NOT TRUE 需要 false 与 NULL 一起时用这个
-- WHERE NOT active NOT NULL 仍是 NULL,NULL 行同样丢失Inside the snippet
At its core this is a single SELECT statement against subscriptions.
Breaking the statements into their working parts: a CTE (WITH … AS) that names an intermediate result before the main query; an ORDER BY that fixes the output order.
Putting it to use
Run it in the subscriptions database context.
Interactive Tools for This Topic
PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.SQL FormatterReformat SQL by uppercasing reserved words and breaking lines before SELECT, FROM, WHERE, and other clauses.
FAQ
- Which objects does the SQL touch?
- The references are `subscriptions`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.