Example 1
List customers who have placed at least one order
Alice has two orders and Bob has one. EXISTS returns TRUE for both because the subquery finds at least one matching row. Carol has no orders so the subquery returns no rows, EXISTS is FALSE, and Carol is excluded. Alice still appears only once even though she has two matching orders, because EXISTS stops checking after the first match.
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 |
Output is identical across all engines.