Example 1
Return each customer once even when many orders exist
Alice has two matching orders, but she still appears once because EXISTS only checks whether at least one related row exists. Bob also appears once. Carol has no orders, so she is excluded. A plain join would return Alice twice unless you added extra deduplication.
CREATE TABLE customers (id INT, name VARCHAR(50));
CREATE TABLE orders (id INT, customer_id INT);
INSERT INTO
customers (id, name)
VALUES
(1, 'Alice'),
(2, 'Bob'),
(3, 'Carol');
INSERT INTO
orders (id, customer_id)
VALUES
(1, 1),
(2, 1),
(3, 2);SELECT
name
FROM
customers c
WHERE
EXISTS (
SELECT
1
FROM
orders o
WHERE
o.customer_id = c.id
)
ORDER BY
name;| name |
|---|
| Alice |
| Bob |
`EXISTS` is used here specifically to avoid duplicate customer rows.