What is the EXISTS Operator?

Before diving into code, think of EXISTS like a yes/no question you ask SQL:

"Does this related record exist somewhere in another table?"

If the answer is yes, the row is included in your result. If the answer is no, the row is skipped.

The EXISTS operator is always used with a subquery — a query inside another query. It checks whether that inner query returns any rows at all. It does not care what those rows contain; it only cares whether at least one exists.

Syntax:

SELECT col_names
FROM table_name
WHERE [NOT] EXISTS (subquery)

Key point: The NOT keyword flips the logic. NOT EXISTS includes a row only when the subquery returns no matching rows.

<aside> 💡

You can write SELECT 1, SELECT *, or SELECT NULL inside the subquery — the result is always the same. MySQL completely ignores what you select inside the subquery. It only checks whether any row comes back.

</aside>

What is a Correlated Subquery?

The subquery used with EXISTS is almost always a correlated subquery. This means the inner query references a column from the outer query. SQL evaluates the subquery once per row in the outer table.

Think of it like a loop:

  1. Take the first row from the outer table.
  2. Run the subquery using that row's values.
  3. If a match is found, include the row in the result.
  4. Move to the next row. Repeat.

This is different from a regular subquery, which runs only once. A correlated subquery runs as many times as there are rows in the outer table.