0PricingLogin
SQL Academy · Lesson

EXISTS and NOT EXISTS

Check for related rows efficiently.

What Is EXISTS?

The EXISTS operator tests whether a subquery returns at least one row. It evaluates to TRUE if the subquery produces any result, and FALSE if the subquery is empty.

Unlike other subquery operators that compare values, EXISTS only cares about presence — it does not look at the actual data returned by the subquery.

Setting Up Sample Tables

Before writing EXISTS queries, let's create two tables: customers and orders. We'll use these throughout the lesson to explore how EXISTS and NOT EXISTS work in practice.

CREATE TABLE customers (
  customer_id INT PRIMARY KEY,
  name        VARCHAR(100),
  country     VARCHAR(50)
);

CREATE TABLE orders (
  order_id    INT PRIMARY KEY,
  customer_id INT,
  amount      DECIMAL(10,2),
  order_date  DATE
);

INSERT INTO customers VALUES
  (1, 'Alice',   'US'),
  (2, 'Bob',     'UK'),
  (3, 'Charlie', 'US'),
  (4, 'Diana',   'DE');

INSERT INTO orders VALUES
  (101, 1, 250.00, '2024-01-10'),
  (102, 1, 180.00, '2024-02-15'),
  (103, 2,  95.00, '2024-03-01'),
  (104, 3, 430.00, '2024-03-22');

All lessons in this course

  1. Correlated Subqueries
  2. EXISTS and NOT EXISTS
  3. IN vs ANY vs ALL
  4. EXISTS vs JOIN Performance
← Back to SQL Academy