SQL IN with Subqueries
An IN subquery lets the database build the allowed-value list from another SELECT instead of hard-coding it by hand.
Earlier, IN matched a column against a short hand-written list.
A subquery can supply that list for you. The outer query asks for products;
the inner query finds the supplier IDs that qualify.
This keeps the logic tied to the data. If a supplier changes state, the subquery result changes automatically. You don't need to copy new IDs into the outer query.
select item_name
from items
where parent_id in (
select parent_id
from parents
where status = 'active'
) The inner query returns the list
An IN subquery should return one column. It may return many
rows, because those rows become the list the outer query checks against. If
you need columns from both tables in the final output, a JOIN
is usually a better fit.
Schema · Garden Shop Tables · suppliers, products 2 tables
One row per supplier. Some suppliers have no contact email.
One row per product, with price, cost, and inventory levels.
Show product_name and supplier_id for products
supplied by suppliers in OR or FL. Use a
subquery against suppliers to find the matching IDs.
Run your query to inspect the result.
Expected answer
- Columns: product_name, supplier_id.
- Rows: products supplied by Oregon or Florida suppliers.
- The list of supplier IDs comes from the suppliers table, not a hand-typed list.
Related
Comparisons, AND/OR, IN, BETWEEN, and LIKE.
SELECT, WHERE, ORDER BY, and LIMIT at a glance.
Practice ranking, running totals, and top row per group.
Debug filters that match nothing.
Filter window results in a CTE or with QUALIFY.
Nested SELECTs, IN, EXISTS, and correlation.