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.

SqlData Fetching

Code

snippet
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

FAQ

Which tables appear in this script?
`customers`, `orders`, combined through a join.