NOT EXISTS Anti Join Versus NOT IN
Use NOT EXISTS for anti joins because a single NULL in a NOT IN subquery makes the predicate UNKNOWN and silently returns an empty result.
Code
-- 找出没有任何订单的用户:orders.user_id 可空(遗留导入行没有归属)
CREATE TABLE users (id bigint PRIMARY KEY, email text NOT NULL);
CREATE TABLE orders (
id bigserial PRIMARY KEY,
user_id bigint, -- 可空
note text
);
INSERT INTO users VALUES (1, '[email protected]'), (2, '[email protected]');
INSERT INTO orders VALUES (1, 1, 'ok'), (2, NULL, 'imported');
-- NOT EXISTS:anti join 语义,NULL 行不影响 EXISTS 判断,结果稳定
SELECT u.id, u.email
FROM users u
WHERE NOT EXISTS (SELECT 1 FROM orders o WHERE o.user_id = u.id);
-- NOT IN:列表里混进一个 NULL 后,2 <> NULL 是 UNKNOWN,整个查询返回空集
SELECT u.id
FROM users u
WHERE u.id NOT IN (SELECT user_id FROM orders); -- 0 行
-- 补救:显式过滤 NULL(WHERE user_id IS NOT NULL),或直接改用 NOT EXISTSWhat the code does
Several statements share this file — SELECT / INSERT / CREATE, with users and orders among the objects involved.
Breaking the statements into their working parts: a WHERE clause narrowing which rows one statement affects; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity.
Applying it
Run the statement against the users table.
Statements that matter
SELECT u.id, u.email
FROM users u
WHERE NOT EXISTS (SELECT 1 FROM orders o WHERE o.user_id = u.id);
CREATE TABLE orders (
id bigserial PRIMARY KEY,
user_id bigint, -- 可空
note text
);
CREATE TABLE users (id bigint PRIMARY KEY, email text NOT NULL);
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 tables appear in this script?
- `users`, `orders` — referenced directly, no join needed.
Report a problem with this exampleOpens a pre-filled issue on GitHub.