Referral funnel SQL: LEFT JOIN date windows and country filters
SQL & DataModel answerLast updated
Write five SQL queries over users, referrals and orders that measure referral conversion and revenue without losing zero-activity rows, with no window functions.
You are analysing a referral program. Treat today as 2025-09-01. Window functions are not allowed. Use LEFT JOIN, COUNT(DISTINCT ...), GROUP BY and HAVING where they fit.
Schema
users(user_id INT PRIMARY KEY, name TEXT, signup_dt DATE, country TEXT)referrals(referrer_user_id INT, referred_user_id INT, referral_dt DATE)orders(order_id INT PRIMARY KEY, user_id INT, order_dt DATE, amount DECIMAL(10,2))
Sample data
users
| user_id | name | signup_dt | country |
|---|---|---|---|
| 1 | Alice | 2025-08-20 | US |
| 2 | Bob | 2025-08-22 | CA |
| 3 | Chen | 2025-08-25 | CN |
| 4 | Diana | 2025-08-29 | US |
| 5 | Eva | 2025-08-31 | GB |
referrals
| referrer_user_id | referred_user_id | referral_dt |
|---|---|---|
| 1 | 2 | 2025-08-22 |
| 1 | 3 | 2025-08-25 |
| 2 | 4 | 2025-08-29 |
| 99 | 5 | 2025-08-31 |
orders
| order_id | user_id | order_dt | amount |
|---|---|---|---|
| 101 | 2 | 2025-08-30 | 50.00 |
| 102 | 2 | 2025-09-01 | 25.00 |
| 103 | 3 | 2025-09-01 | 10.00 |
| 104 | 4 | 2025-08-29 | 20.00 |
Tasks
Write the exact SQL for each part.
A) Referrer performance, last 7 days. For every referrer_user_id in referrals, return:
referred_count: distinct referred users.buyers_last_7d: distinct referred users with an order between2025-08-26and2025-09-01inclusive.revenue_last_7d: the sum of order amounts in that window.
Referrers with no buyers or revenue must still appear. Group only by referrer_user_id.
B) Referred users who never bought. List every referred user who has no orders on or before 2025-09-01. Output referred_user_id, referrer_user_id. Use a LEFT JOIN to orders and enforce the "zero" condition with HAVING.
C) Conversion by country. Among referred users only, return per country:
referred_usersbuyers: users with at least one order on or before2025-09-01.conversion_rate:buyers * 1.0 / referred_users, rounded to 2 decimals.
Keep countries with zero buyers. Exclude countries with no referred users.
D) A filter that may match nothing. The business asks for the metrics from part C for country = 'UK'. Without assuming the code list:
- Write the query you would run first to discover which country values exist.
- Write the corrected metrics query using the value that actually appears in the data (the sample uses
GB). - Add a short SQL comment explaining why a naive
WHERE country = 'UK'can silently return nothing or zero.
E) Read-only exploration. Suppose only a reviewer can execute queries on a shared screen. Write the first two exploratory SELECTs you would ask them to run to understand table shape and safe join keys before attempting A to D.
Hints
Hint 1
When a LEFT JOIN is filtered on the right-hand table, the filter must go in the ON clause. In WHERE it removes the NULL-padded rows and silently turns the join into an inner join.
Hint 2
COUNT(*) counts the NULL-padded row as 1, while COUNT(o.order_id) and COUNT(DISTINCT o.user_id) ignore NULLs. That is the key to the HAVING condition in B and the buyer counts in A and C.
Hint 3
Joining one referred user to several orders multiplies rows. COUNT(DISTINCT) protects the counts but not SUM, so dedupe the referral pairs first and wrap the sum in COALESCE.
Hint 4
A filter on the driving (preserved) table, such as users.country, is safe in WHERE. Before filtering on a categorical value, profile the column with GROUP BY plus LENGTH or TRIM to spot variants and whitespace.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Core rule
In a LEFT JOIN, conditions on the right-hand table go in ON; conditions on the preserved (left) table can go in WHERE. If you put the order-date window in WHERE, every row whose order columns are NULL is discarded, so referrers and users with no orders vanish.
Three related traps appear in every part:
- NULL counting.
COUNT(*)counts a NULL-padded row as 1.COUNT(o.order_id)gives 0. - Fan-out. One referred user with several orders produces several rows.
COUNT(DISTINCT ...)is safe against this, butSUMis not. - Silent empty filters. A predicate on a value that does not exist returns no rows and raises no error.
A) Referrer metrics
SELECT
r.referrer_user_id,
COUNT(DISTINCT r.referred_user_id) AS referred_count,
COUNT(DISTINCT o.user_id) AS buyers_last_7d,
COALESCE(SUM(o.amount), 0) AS revenue_last_7d
FROM (SELECT DISTINCT referrer_user_id, referred_user_id
FROM referrals) r
LEFT JOIN orders o
ON o.user_id = r.referred_user_id
AND o.order_dt BETWEEN '2025-08-26' AND '2025-09-01'
GROUP BY r.referrer_user_id;
If order_dt were a timestamp, I would switch to a half-open range (>= '2025-08-26' AND < '2025-09-02') so orders late on 09-01 are not cut off.
Result on the sample: referrer 1 gives (2, 2, 85.00), referrer 2 gives (1, 1, 20.00), and referrer 99 gives (1, 0, 0).
- The
DISTINCTsubquery stops duplicate referral rows from double-counting revenue. COALESCEturns the NULL sum for referrer 99 into 0.- If one user could be referred by two referrers, their revenue would be credited to both. That is a business attribution question worth flagging.
B) Referred users with no orders
SELECT r.referred_user_id, r.referrer_user_id
FROM referrals r
LEFT JOIN orders o
ON o.user_id = r.referred_user_id
AND o.order_dt <= '2025-09-01'
GROUP BY r.referred_user_id, r.referrer_user_id
HAVING COUNT(o.order_id) = 0;
The result is (5, 99). Using HAVING COUNT(*) = 0 would be a bug, because the NULL-padded row makes the count 1 and the query returns nothing. WHERE o.order_id IS NULL is an equivalent anti-join, but the task asks for HAVING.
C) Conversion by country
SELECT
u.country,
COUNT(DISTINCT u.user_id) AS referred_users,
COUNT(DISTINCT o.user_id) AS buyers,
ROUND(COUNT(DISTINCT o.user_id) * 1.0
/ COUNT(DISTINCT u.user_id), 2) AS conversion_rate
FROM users u
JOIN (SELECT DISTINCT referred_user_id FROM referrals) r
ON r.referred_user_id = u.user_id
LEFT JOIN orders o
ON o.user_id = u.user_id
AND o.order_dt <= '2025-09-01'
GROUP BY u.country
HAVING COUNT(DISTINCT u.user_id) > 0;
| country | referred_users | buyers | conversion_rate |
|---|---|---|---|
| CA | 1 | 1 | 1.00 |
| CN | 1 | 1 | 1.00 |
| US | 1 | 1 | 1.00 |
| GB | 1 | 0 | 0.00 |
- The inner join to the deduped referred set means Alice (US, never referred) is not counted, so US shows 1 referred user.
- The
LEFT JOINto orders keeps GB with zero buyers. * 1.0avoids integer division, which would break for rates such as 1/3.- The
HAVINGclause is redundant with the inner join, but it states the requirement explicitly. - Referred users missing from
userscannot get a country and are dropped. That is a data-quality caveat to mention.
D) The 'UK' trap
Discover the real values first:
SELECT country, LENGTH(country) AS len, COUNT(*) AS n_users
FROM users
GROUP BY country, LENGTH(country)
ORDER BY n_users DESC;
The LENGTH column exposes trailing spaces such as 'GB '. The output shows GB and no UK. A broader probe is WHERE UPPER(TRIM(country)) IN ('UK','GB','GBR','UNITED KINGDOM').
Then run the corrected metrics:
-- WHERE country = 'UK' is not an error: the predicate is false for every row,
-- so the result is empty (or a 0 if aggregated without GROUP BY). The data uses
-- ISO alpha-2 'GB', so a "0 UK conversions" report would be a false finding.
SELECT
u.country,
COUNT(DISTINCT u.user_id) AS referred_users,
COUNT(DISTINCT o.user_id) AS buyers,
ROUND(COUNT(DISTINCT o.user_id) * 1.0
/ COUNT(DISTINCT u.user_id), 2) AS conversion_rate
FROM users u
JOIN (SELECT DISTINCT referred_user_id FROM referrals) r
ON r.referred_user_id = u.user_id
LEFT JOIN orders o
ON o.user_id = u.user_id
AND o.order_dt <= '2025-09-01'
WHERE u.country = 'GB'
GROUP BY u.country;
Result: GB | 1 | 0 | 0.00. Here the country filter is safe in WHERE because it constrains the preserved table, not the LEFT-joined one.
E) Two exploratory queries
1. Shape, key uniqueness and date range.
SELECT
(SELECT COUNT(*) FROM users) AS user_rows,
(SELECT COUNT(DISTINCT user_id) FROM users) AS distinct_user_ids,
(SELECT COUNT(*) FROM referrals) AS referral_rows,
(SELECT COUNT(*) FROM orders) AS order_rows,
(SELECT MIN(order_dt) FROM orders) AS first_order,
(SELECT MAX(order_dt) FROM orders) AS last_order,
(SELECT COUNT(*) FROM orders WHERE order_dt > '2025-09-01') AS future_orders;
This confirms user_id is unique (no fan-out from users), shows how big the tables are, and reveals whether any orders fall after "today".
2. Join-key integrity in referrals.
SELECT
COUNT(*) AS referral_rows,
COUNT(DISTINCT r.referred_user_id) AS distinct_referred,
SUM(CASE WHEN ur.user_id IS NULL THEN 1 ELSE 0 END) AS referrer_missing_in_users,
SUM(CASE WHEN ud.user_id IS NULL THEN 1 ELSE 0 END) AS referred_missing_in_users
FROM referrals r
LEFT JOIN users ur ON ur.user_id = r.referrer_user_id
LEFT JOIN users ud ON ud.user_id = r.referred_user_id;
On the sample this returns 4, 4, 1 (referrer 99) and 0. It tells me whether a referred user can appear twice (so I must dedupe before summing) and whether orphan referrers exist, which is why A must group on referrals rather than join to users.
Common mistakes
- Date window or
o.order_id IS NOT NULLinWHERE, which collapses the LEFT JOIN. COUNT(*)instead ofCOUNT(o.order_id)in theHAVING.- Forgetting
COALESCE, so zero-revenue referrers show NULL. - Summing amounts after a join without deduplicating the referral pairs.
- Trusting a filter value without profiling the column first.