sql · level 2 · unit 4 · lesson 3
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
A subquery can build the list that IN checks.
IN needs a list. Instead of typing one, let a subquery make it. WHERE id IN (SELECT customer_id FROM orders) keeps every customer whose id appears anywhere in orders.
The gives back one column, with any number of rows. The then checks each of its own rows against that list.
NOT IN with a subquery finds what is missing, like an anti-join. Make sure the inner query's column holds no NULLs, or NOT IN matches nothing.
SELECT name FROM customers
WHERE id IN (SELECT customer_id FROM orders)
ORDER BY name; Repeats in the list do not matter. A customer passes once, however many times their id appears.
guess first
Who has ordered pancakes?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
SELECT name FROM customers
WHERE id IN (SELECT customer_id FROM orders WHERE dish_id = 3)
ORDER BY name;
your turn
Your turn. Who ordered a brownie?
The brownie has the id 5. Type IN to find who ordered one, or NOT IN to find who never did.
result
Your answer appears here as a table.
fix it
Which dishes have been ordered? Fix it!
result
Your answer appears here as a table.
- Read the error. How many columns does the inner query give back?
INchecks one value against one list, so the inner query may give back one column only.- Delete , quantity from the inner query, then press run.
nailed it
a query built your list for you. :D
IN (SELECT ...)lets a query build the list.- The inner query must give back exactly one column.
NOT IN (SELECT ...)finds rows with no match.
new words in your collection
- inner query
- outer query
This lesson isn’t saved. A free account remembers every lesson you finish.