Find the latest signup from each source
Your task
Return source, id as customer_id, and signup_date for the latest signup in each source. Prefer the larger ID on a tie. Sort by source.
A correlated subquery can compare one customer with other customers from the same source.
Sample data
customers| id | name | signup_date | source |
|---|---|---|---|
| 1 | Avery | 2025-01-02 | organic |
| 2 | Casey | 2025-01-05 | |
| 3 | Jordan | 2025-01-12 | organic |
| 4 | Morgan | 2025-02-01 | |
| 5 | Riley | 2025-02-10 | social |
| 6 | Sam | 2025-02-20 | organic |
| 7 | Taylor | 2025-03-01 | social |
| 8 | Devon | 2025-02-07 |
Expected output
| source | customer_id | signup_date |
|---|---|---|
| 8 | 2025-02-07 | |
| organic | 6 | 2025-02-20 |
| social | 7 | 2025-03-01 |
Show a hint
Use NOT EXISTS to rule out a later signup or a tied signup with a larger ID.
Subqueries and CTEs guide
Use a query as a value
An aggregate without GROUP BY produces one row. A single-column subquery can therefore provide a scalar value for a comparison. Here each price is compared with an average calculated across the whole table.
SELECT title, price
FROM albums
WHERE price < (SELECT AVG(price) FROM albums);Ask whether a related row exists
An EXISTS subquery only needs to produce one row to be true. It refers to a.id from the outer query, so the test is evaluated for the current album. The expression in the inner SELECT is immaterial to the existence test.
SELECT a.title
FROM albums AS a
WHERE EXISTS (
SELECT 1
FROM sales AS s
WHERE s.album_id = a.id AND s.quantity > 1
);Name intermediate results with WITH
A common table expression gives an intermediate query a name for a single statement. Here the CTE summarizes sales before joining them to albums. Read the CTE on its own first, then read the final SELECT to see how the summary is used.
WITH totals AS (
SELECT album_id, SUM(quantity) AS copies
FROM sales
GROUP BY album_id
)
SELECT a.title, COALESCE(t.copies, 0) AS copies
FROM albums AS a
LEFT JOIN totals AS t ON t.album_id = a.id;Worked solution
SELECT c.source,c.id AS customer_id,c.signup_date FROM customers c WHERE NOT EXISTS (SELECT 1 FROM customers x WHERE x.source=c.source AND (x.signup_date>c.signup_date OR (x.signup_date=c.signup_date AND x.id>c.id))) ORDER BY c.source;Press Control+Space for SQL suggestions. Use the arrow keys to select an option and Enter to insert it.
Results
Loading SQLite…
