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.

SqlData Integrity

Code

snippet
-- 找出没有任何订单的用户: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 EXISTS

What 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

FAQ

Which tables appear in this script?
`users`, `orders` — referenced directly, no join needed.