Keep unmatched rows after filtering
Your task
Return each album title and the ID of any sale of at least three copies, with NULL when there is no such sale.
Filtering the right table in ON keeps unmatched left rows. The same filter in WHERE would discard them.
Sample data
| id | title | genre | price | stock |
|---|---|---|---|---|
| 1 | Night Bus | Jazz | 18 | 7 |
| 2 | Static Bloom | Indie | 22 | 4 |
| 3 | Soft Circuit | Electronic | 24 | 0 |
| 4 | Blue Hour | Jazz | 16 | 3 |
| 5 | Coastline | Indie | 19 | 8 |
| 6 | Low Tide | Ambient | 21 | 2 |
Expected output
| title | id |
|---|---|
| Night Bus | 103 |
| Static Bloom | NULL |
| Soft Circuit | NULL |
| Blue Hour | NULL |
| Coastline | NULL |
| Low Tide | NULL |
Show a hint
Put the quantity filter inside the LEFT JOIN's ON clause.
Joins and set operations guide
Match rows by a key
A join combines columns horizontally. The condition links sales.album_id to albums.id. If an album has three sale records, a join can return its title three times.
SELECT s.id AS sale_id, a.title, s.quantity
FROM sales AS s
JOIN albums AS a ON a.id = s.album_id;Preserve rows without a match
A LEFT JOIN retains each album. The quantity condition belongs in ON because it defines which sales qualify as matches. Placing it in WHERE would also remove albums whose sale columns are NULL.
SELECT a.title, s.id AS large_sale_id
FROM albums AS a
LEFT JOIN sales AS s
ON s.album_id = a.id
AND s.quantity >= 3;Combine result sets vertically
UNION stacks compatible result sets and removes duplicate rows. UNION ALL keeps every row. INTERSECT keeps shared rows, and EXCEPT keeps rows unique to the first result. With set operations, both inputs must return the same number of columns.
SELECT title FROM albums WHERE genre = 'Jazz'
UNION
SELECT title FROM albums WHERE price < 20;Worked solution
SELECT a.title, s.id FROM albums a LEFT JOIN sales s ON s.album_id = a.id AND s.quantity >= 3;Press Control+Space for SQL suggestions. Use the arrow keys to select an option and Enter to insert it.
Results
Loading SQLite…
