Find buyers active in exactly one month
Your task
Return customer IDs with completed orders in exactly one of January and February 2025. Ignore orders in other months and sort by customer ID.
The symmetric difference contains members of either set, excluding their overlap.
Sample data
shop_orders| id | customer_id | ordered_on | channel | status | total_cents |
|---|---|---|---|---|---|
| 201 | 1 | 2025-01-04 | online | completed | 2500 |
| 202 | 2 | 2025-01-10 | store | completed | 1800 |
| 203 | 2 | 2025-01-10 | store | completed | 3200 |
| 204 | 3 | 2025-01-18 | marketplace | refunded | 5000 |
| 205 | 4 | 2025-02-02 | store | completed | 2700 |
| 206 | 1 | 2025-02-04 | online | completed | 4000 |
| 207 | 5 | 2025-02-18 | online | cancelled | 2400 |
| 208 | 6 | 2025-02-28 | online | completed | 1700 |
| 209 | 4 | 2025-03-16 | online | completed | 2900 |
| 210 | 8 | 2025-03-09 | store | completed | 3100 |
Expected output
| customer_id |
|---|
| 2 |
| 4 |
| 6 |
Show a hint
Build January and February buyer sets, then keep customers that occur in exactly one set.
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
WITH jan AS (SELECT DISTINCT customer_id FROM shop_orders WHERE status='completed' AND ordered_on>='2025-01-01' AND ordered_on<'2025-02-01'), feb AS (SELECT DISTINCT customer_id FROM shop_orders WHERE status='completed' AND ordered_on>='2025-02-01' AND ordered_on<'2025-03-01'), both_sets AS (SELECT customer_id FROM jan UNION ALL SELECT customer_id FROM feb) SELECT customer_id FROM both_sets GROUP BY customer_id HAVING COUNT(*)=1 ORDER BY customer_id;Press Control+Space for SQL suggestions. Use the arrow keys to select an option and Enter to insert it.
Results
Loading SQLite…
