Filtering joins
- SQL course
- Intermediate
- Lesson 5/115
- 4 min
Use WHERE together with JOIN.
Join filtering
You filter a JOIN result with WHERE. The JOIN runs first, then WHERE narrows the result.
SELECT o.id, c.name
FROM orders o
INNER JOIN customers c ON o.customer_id = c.id
WHERE c.city = 'İstanbul';This query returns orders from Istanbul customers.
o.id, c.name is selected from orders o. customers c is joined on o.customer_id = c.id, keeping only matching rows. WHERE keeps only the rows where c.city = 'İstanbul' holds.
Join filtering — details
The join condition goes in ON, the row filter in WHERE. Mixing them can slow the query.
For example, ON o.customer_id = c.id links the tables, while WHERE c.city = 'İstanbul' limits the result to customers in Istanbul.
Practice Join filtering
Filter the JOIN result where city = 'İstanbul'.
Starter code
-- join and filter
SELECT o.id, c.name
FROM orders o
INNER JOIN customers c ON o.customer_id = c.idSample solution
SELECT o.id, c.name
FROM orders o
INNER JOIN customers c ON o.customer_id = c.id
WHERE c.city = 'İstanbul';Expected output
id name 1 Ayşe 3 Zeynep
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Add the filter
SELECT o.id, c.name
FROM orders o
INNER JOIN customers c ON o.customer_id = c.id
____ c.city = 'İstanbul';
SELECT o.id, c.name
FROM orders o
INNER JOIN customers c ON o.customer_id = c.id
WHERE c.city = 'İstanbul';
Explanation: After the JOIN, WHERE filters the result; only customers in Istanbul remain.
2 Filtering joins: match the terms
| Term | Meaning |
|---|---|
ON |
join |
WHERE |
row filter |
HAVING |
group filter |
JOIN |
table |
3 Where does the row filter go?
- FROM
- ON
- SELECT
- WHERE Correct answer
Explanation: The row filter goes in WHERE.