typestar

Subquery in WHERE in SQL

A subquery computes the list of values the outer filter matches against.

SELECT
    id,
    name,
    email
FROM customers
WHERE id IN (
    SELECT customer_id
    FROM orders
    WHERE total > 1000
)
ORDER BY name;

How it works

  1. The inner query runs first and hands its rows to IN.
  2. It must select exactly one column.
  3. This is often clearer than a join when you want no extra columns.

Keywords and builtins used here

The run, in numbers

Lines
11
Characters to type
118
Tokens
25
Three-star pace
90 tpm

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

Type this snippet

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

Next →