typestar

EXISTS and NOT EXISTS in SQL

EXISTS asks whether any matching row exists, and stops at the first one.

SELECT
    c.id,
    c.name
FROM customers AS c
WHERE NOT EXISTS (
    SELECT 1
    FROM orders AS o
    WHERE o.customer_id = c.id
      AND o.placed_at >= '2026-01-01'
)
ORDER BY c.name;

How it works

  1. It ignores what the subquery selects, only whether it returns a row.
  2. NOT EXISTS is the safe way to say has none of these.
  3. Unlike NOT IN, it behaves sanely when NULLs are involved.

Keywords and builtins used here

The run, in numbers

Lines
11
Characters to type
162
Tokens
44
Three-star pace
90 tpm

At the three-star pace of 90 tokens a minute, this run takes about 29 seconds.

Type this snippet

Step 3 of 3 in Subqueries, step 3 of 24 in Analytics & reporting.

← Previous Next →