sqlcmd.net validated sql reference
advanced filtering MySQL MariaDB SQL Server PostgreSQL SQLite

Test For Row Existence With EXISTS

Use a correlated subquery inside `EXISTS` to include rows only when related rows are found in another table.

Docker-validated Not currently validation-green

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.

Rows loaded before the example query runs.
Setup
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);
Shared across supported engines.
SQL
SELECT
  name
FROM
  customers c
WHERE
  EXISTS (
    SELECT
      1
    FROM
      orders o
    WHERE
      o.customer_id = c.id
  )
ORDER BY
  name;
Returned rows for the shared example.
name
Alice
Bob

Output is identical across all engines.

Where this command helps.

  • keeping rows only when a related record exists
  • avoiding duplicate outer rows when multiple related matches are possible

What the command is doing.

EXISTS takes a subquery and returns TRUE if that subquery produces at least one row. It is typically used as a WHERE filter with a correlated subquery that references the outer query's current row. Unlike a JOIN, EXISTS does not multiply rows when multiple matches exist — it is purely a presence check.