EXISTS Semi Join Existence Filter
Filter outer rows with EXISTS (SELECT 1 ...) as a semi join: matching rows prove existence and stop early without duplicating outer rows like an inner join.
Code
CREATE TABLE customers (
id int PRIMARY KEY,
name text NOT NULL
);
CREATE TABLE orders (
id int PRIMARY KEY,
customer_id int NOT NULL REFERENCES customers(id),
total_cents int NOT NULL
);
INSERT INTO customers VALUES (1, 'ada'), (2, 'raj'), (3, 'kim');
INSERT INTO orders VALUES
(100, 1, 2500),
(101, 1, 1800),
(102, 2, 9000);
-- semi join 语义:EXISTS 是存在性测试,子查询命中即停,
-- 外层行不会被匹配行数复制放大
SELECT c.id, c.name
FROM customers c
WHERE EXISTS (
SELECT 1
FROM orders o
WHERE o.customer_id = c.id
)
ORDER BY c.id;
-- 对照:内连接按匹配行数放大,ada 出现两次
SELECT c.id, c.name
FROM customers c
JOIN orders o ON o.customer_id = c.id
ORDER BY c.id;How the snippet works
The file runs SELECT / INSERT / CREATE statements, touching customers and orders.
Clause by clause, expect: one JOIN combining rows across tables; a WHERE clause deciding which rows the statement applies to; an ORDER BY that fixes the output order; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity; a foreign-key REFERENCES guard that anchors child rows to the parent table.
Applying it
Run the statement against the customers table.
Statements that matter
SELECT c.id, c.name
FROM customers c
WHERE EXISTS (
SELECT 1
FROM orders o
WHERE o.customer_id = c.id
)
ORDER BY c.id;
SELECT c.id, c.name
FROM customers c
JOIN orders o ON o.customer_id = c.id
ORDER BY c.id;
CREATE TABLE orders (
id int PRIMARY KEY,
customer_id int NOT NULL REFERENCES customers(id),
total_cents int 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?
- `customers`, `orders`, combined through a join.
Report a problem with this exampleOpens a pre-filled issue on GitHub.