Outer Join Filter Placement ON Versus WHERE
Right-table filters belong in ON, not WHERE: a WHERE on the right side of a LEFT JOIN discards unmatched rows and silently turns it into an inner join.
Code
-- 外连接里右表条件放 ON 还是 WHERE,结果行数完全不同
SELECT
u.id,
u.email,
count(o.id) AS order_count
FROM users u
LEFT JOIN orders o
ON o.user_id = u.id
AND o.status = 'paid' -- 条件在 ON:没有付费订单的用户也保留,计为 0
WHERE u.created_at >= '2026-01-01'
GROUP BY u.id, u.email
ORDER BY order_count DESC;
-- 同样的条件改写进 WHERE:右表列上 IS NULL 的行被过滤掉,
-- LEFT JOIN 退化成 INNER JOIN,从未下单的用户从结果里消失
SELECT
u.id,
count(o.id) AS order_count
FROM users u
LEFT JOIN orders o ON o.user_id = u.id
WHERE o.status = 'paid' -- 位置错了:右表列出现在 WHERE
GROUP BY u.id
ORDER BY order_count DESC;What the code does
Several statements share this file — SELECT, with users and orders among the objects involved.
Breaking the statements into their working parts: 2 JOINs combining rows across tables; a WHERE clause narrowing which rows one statement affects; COUNT aggregation; a GROUP BY that collapses matching rows into one output row per group; an ORDER BY that fixes the output order.
Watch out for
- 2 joins multiply the intermediate row count; confirm the join keys are indexed before pointing this at production-sized tables.
Applying it
Run the statement against the users table.
Statements that matter
SELECT
u.id,
count(o.id) AS order_count
FROM users u
LEFT JOIN orders o ON o.user_id = u.id
WHERE o.status = 'paid' -- 位置错了:右表列出现在 WHERE
GROUP BY u.id
ORDER BY order_count DESC;
SELECT
u.id,
u.email,
count(o.id) AS order_count
FROM users u
LEFT JOIN orders o
ON o.user_id = u.id
AND o.status = 'paid' -- 条件在 ON:没有付费订单的用户也保留,计为 0
WHERE u.created_at >= '2026-01-01'
GROUP BY u.id, u.email
ORDER BY order_count DESC;
Interactive Tools for This Topic
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.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.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 does the SQL touch?
- `users`, `orders`, combined through 2 joins.
Report a problem with this exampleOpens a pre-filled issue on GitHub.