runtime
29 / 88

lesson 29 Dates, strings & subqueries · intermediate

Ask whether a row exists

Test whether matching rows exist without duplicating results.

the idea

EXISTS is true when its subquery returns at least one row. A correlated subquery refers to the outer row. NOT EXISTS is useful for finding missing relationships.

tables in this lesson

The challenges use this data. Each column shows its type underneath; → marks a link to another table.

customers4 columns · 8 rows
idinteger · keynametextcitytextjoined_attext
1AliceChicago2024-01-10
2BenAustin2024-02-12
3CaraSeattle2024-03-05
4DevChicago2024-04-20
5ElenaNULL2024-05-01

showing 5 of 8 rows

orders6 columns · 12 rows
idinteger · keycustomer_idintegerproduct_idintegerquantityintegerstatustextordered_attext
101112paid2025-01-01
102231paid2025-01-02
103121paid2025-01-05
104352pending2025-01-08
105445paid2025-02-01

showing 5 of 12 rows

example

The idea in one query. Press Run to see what it returns; running examples never affects your progress.

example.sql
SELECT c.name
FROM customers c
WHERE EXISTS (
  SELECT 1
  FROM orders o
  WHERE o.customer_id=c.id AND o.status='paid'
);

Watch for: A join may duplicate customer names; EXISTS preserves one outer row.

build it step by step

Each step changes one thing. Run them in order and watch the result change.

  1. Check for a matching paid order. EXISTS asks whether at least one related row satisfies the inner filter. It does not multiply the outer customer rows.

    step-1.sql
    SELECT c.id, c.name, o.id AS order_id, o.status
    FROM customers c
    LEFT JOIN orders o ON o.customer_id = c.id AND o.status = 'paid'
    ORDER BY c.id
    LIMIT 12;
  2. Keep customers with a match. EXISTS returns true when the correlated subquery finds one or more rows. The outer SELECT lists those customers once.

    step-2.sql
    SELECT c.name
    FROM customers c
    WHERE EXISTS (
      SELECT 1
      FROM orders o
      WHERE o.customer_id = c.id AND o.status = 'paid'
    );

challenge 1

Show name of customers who have at least one paid order.

Return nameany row order

challenge-1.sql
 
To master this lesson, solve both challenges without hints and pass the concept check. 3 of 3 to go.