Referral Attribution Metrics Using Left Joins
Medium · Data Manipulation (SQL/Python) · Data Scientist · Technical Screen
Problem Statement
A commerce platform tracks customer signups, referral invitations, and completed purchases across three tables: users, referrals, and orders. Assume the reporting reference date is '2025-09-01', so the trailing 7-day inclusive purchase window spans '2025-08-26' through '2025-09-01'.
Without using SQL window functions (such as ROW_NUMBER, RANK, or any OVER (...) clause), write a SQL query that returns one summary row for every distinct referrer_user_id appearing in referrals with four columns:
referrer_user_id: identifier of the referring user.referred_count: total number of distinctreferred_user_idvalues linked to that referrer inreferralsacross all dates.buyers_last_7d: number of distinct referred users of that referrer who placed at least one order withorder_dtbetween'2025-08-26'and'2025-09-01'inclusive.revenue_last_7d: sum ofamountacross orders placed by that referrer's referred users between'2025-08-26'and'2025-09-01'inclusive (0when no qualifying orders exist).
Important requirements:
- Referrers whose referred users placed zero orders inside '2025-08-26' .. '2025-09-01' (or whose referrer_user_id does not appear in users) must still be returned with buyers_last_7d = 0 and revenue_last_7d = 0.
- referrals is not guaranteed to be deduplicated: if the same (referrer_user_id, referred_user_id) pair appears multiple times, neither referred_count nor revenue_last_7d may be double-counted.
- Output rows may be returned in any order.
Input Schema
users
| Column | Type | Description |
|---|---|---|
user_id |
INTEGER |
Primary key for registered accounts |
name |
VARCHAR |
Display name of the account |
signup_dt |
DATE |
Account creation date ('YYYY-MM-DD') |
country |
VARCHAR |
Two-letter country code (for example, 'US', 'DE', 'JP', 'GB') |
referrals
| Column | Type | Description |
|---|---|---|
referrer_user_id |
INTEGER |
Identifier of the user who sent the referral |
referred_user_id |
INTEGER |
Identifier of the user who was referred |
referral_dt |
DATE |
Date the referral event was logged ('YYYY-MM-DD') |
orders
| Column | Type | Description |
|---|---|---|
order_id |
INTEGER |
Primary key of the purchase order |
user_id |
INTEGER |
Identifier of the purchasing user |
order_dt |
DATE |
Date the order was placed ('YYYY-MM-DD') |
amount |
DECIMAL(10,2) |
Monetary total of the order |
Examples
Example 1
Input (users):
user_id |
name |
signup_dt |
country |
|---|---|---|---|
| 10 | 'Maya' |
'2025-08-12' |
'US' |
| 11 | 'Liam' |
'2025-08-18' |
'DE' |
| 12 | 'Noah' |
'2025-08-24' |
'JP' |
| 13 | 'Sofia' |
'2025-08-27' |
'US' |
| 14 | 'Zara' |
'2025-08-30' |
'GB' |
Input (referrals):
referrer_user_id |
referred_user_id |
referral_dt |
|---|---|---|
| 10 | 11 | '2025-08-18' |
| 10 | 11 | '2025-08-19' |
| 10 | 12 | '2025-08-24' |
| 11 | 13 | '2025-08-27' |
| 77 | 14 | '2025-08-30' |
Input (orders):
order_id |
user_id |
order_dt |
amount |
|---|---|---|---|
| 501 | 11 | '2025-08-28' |
40.00 |
| 502 | 11 | '2025-09-01' |
15.00 |
| 503 | 12 | '2025-08-25' |
30.00 |
| 504 | 13 | '2025-08-31' |
60.00 |
Expected Output:
referrer_user_id |
referred_count |
buyers_last_7d |
revenue_last_7d |
|---|---|---|---|
| 10 | 2 | 1 | 55 |
| 11 | 1 | 1 | 60 |
| 77 | 1 | 0 | 0 |
Explanation:
- Referrer 10 referred two unique users (11 and 12; the duplicate (10, 11) row is collapsed). Within '2025-08-26' .. '2025-09-01', user 11 placed two orders totaling 40 + 15 = 55, while user 12's order on '2025-08-25' falls outside the 7-day window, yielding buyers_last_7d = 1 and revenue_last_7d = 55.
- Referrer 11 referred user 13, who placed one 60.00 order on '2025-08-31'.
- Referrer 77 (absent from users) referred user 14, who placed zero orders, so 77 still appears with buyers_last_7d = 0 and revenue_last_7d = 0.
Constraints
- SQL window functions (
OVER (...)) are disallowed; rely on joins,GROUP BY,COUNT(DISTINCT ...), andSUM. - Both window endpoints
'2025-08-26'and'2025-09-01'are inclusive. - If
referralsis empty, return zero rows; ifordersis empty, return every referrer fromreferralswith0buyers and0revenue. - Write standard SQL compatible with SQLite.
Step-by-step walkthrough
Understand the goal and constraints
With the reporting reference date fixed at
'2025-09-01', we must summarize referral performance over the 7-day inclusive window'2025-08-26' .. '2025-09-01'for everyreferrer_user_idpresent inreferrals:Output columns (one row per referrer_user_id in referrals): - referrer_user_id : user ID of the referrer - referred_count : total distinct users ever referred by this referrer - buyers_last_7d : distinct referred users with >= 1 order in '2025-08-26'..'2025-09-01' - revenue_last_7d : sum of order amounts from those referred users in '2025-08-26'..'2025-09-01' (0 if none)Three strict rules shape our query: 1. Keep zero-order referrers: referrers whose referred users placed zero orders in the 7-day window (such as referrer
77in Example 1) must still appear with0buyers and0revenue. 2. Never double-count duplicate referral rows: when(10, 11)appears twice inreferrals, user11's order revenue must still be summed only once. 3. No window functions allowed: solve usingLEFT JOIN,COUNT(DISTINCT ...),SUM, andGROUP BY.Spot the two traps in a naive LEFT JOIN
Most candidates begin with a draft that joins
referralsdirectly toordersand places the date filter inWHERE:-- BROKEN DRAFT: contains two classic SQL bugs! SELECT r.referrer_user_id, COUNT(DISTINCT r.referred_user_id) AS referred_count, COUNT(DISTINCT o.user_id) AS buyers_last_7d, SUM(o.amount) AS revenue_last_7d FROM referrals AS r LEFT JOIN orders AS o ON o.user_id = r.referred_user_id WHERE o.order_dt BETWEEN '2025-08-26' AND '2025-09-01' GROUP BY r.referrer_user_idWhy does this broken draft fail on Example 1? 1.
WHEREsilently destroys theLEFT JOIN: for referrer77(who referred user14, with zero orders),LEFT JOINproduces a row whereo.order_dt = NULL. ThenWHEREruns after the join:NULL BETWEEN '2025-08-26' AND '2025-09-01'is not true, so SQL deletes referrer77's row completely! Even worse, for(10, 12), user12's only order is on'2025-08-25', soWHEREdeletes(10, 12)and shrinks referrer10'sreferred_countfrom2down to1! 2. Duplicate referral rows multiplySUM(o.amount): in Example 1,(10, 11)appears on both'2025-08-18'and'2025-08-19', while user11placed orders of40and15(55total). Joining rawreferralsmatches both orders twice (55 * 2 = 110).COUNT(DISTINCT ...)masks the duplicate in the counts whileSUM(o.amount)silently doubles from55to110!Let's fix one bug at a time.
Deduplicate referral pairs before joining
A referrer's invited audience is defined by the unique set of
(referrer_user_id, referred_user_id)pairs. We collapsereferralsfirst inside a Common Table Expression (CTE) — a temporary named table introduced withWITH:WITH pairs AS ( -- Deduplicate (referrer, referred) pairs first so duplicate referral logs never multiply order amounts SELECT DISTINCT referrer_user_id, referred_user_id FROM referrals )Notice two crucial details: -
referral_dtis excluded intentionally: in Example 1,(10, 11)was logged on both'2025-08-18'and'2025-08-19'. Keepingreferral_dtwould leave two rows for(10, 11)and still double user11's order revenue. - WhySUM(DISTINCT o.amount)is NOT a valid fix: if user11placed two genuinely separate20.00orders (order_id801and802),SUM(DISTINCT o.amount)would collapse them into20.00instead of40.00! Deduplicatingpairsbefore joining counts every real order once.Keep zero-order pairs by filtering dates in ON
Next, we
LEFT JOINpairstoordersand place the 7-day date predicate insideON, never inWHERE:Trace pair (10, 12), where user 12's only order was on 2025-08-25 (outside the window): Filter in WHERE (wrong): 1. LEFT JOIN attaches order (503, 2025-08-25, 30.00) to (10, 12) 2. WHERE checks 2025-08-25 BETWEEN 08-26 AND 09-01 -> FALSE -> row deleted! User 12 vanishes! Filter in ON (right): 1. ON checks user_id = 12 AND order_dt BETWEEN 08-26 AND 09-01 -> no order matches 2. LEFT JOIN keeps (10, 12) and pads order columns with NULL -> (10, 12, NULL, NULL, NULL) 3. User 12 stays in referred_count (= 2) while contributing 0 buyers and 0 revenue!In SQLite and standard SQL, ISO
'YYYY-MM-DD'dates compare chronologically, andBETWEENincludes both'2025-08-26'and'2025-09-01':FROM pairs AS p -- Filter order_dt inside ON (not WHERE) so referrers with no orders in the window keep their row LEFT JOIN orders AS o ON o.user_id = p.referred_user_id AND o.order_dt BETWEEN '2025-08-26' AND '2025-09-01'Aggregate counts and revenue per referrer
Finally, we
GROUP BY p.referrer_user_idand compute all three metrics:COUNT(DISTINCT p.referred_user_id) AS referred_count: even after deduplicatingpairs, user11matches 2 orders in the window and produces 2 joined rows;DISTINCTensures user11still counts as1referred user.COUNT(DISTINCT o.user_id) AS buyers_last_7d:o.user_idis non-NULLonly on rows where a window order matched. BecauseCOUNTignoresNULLs andDISTINCTcollapses repeat orders by user11, referrers without window orders cleanly receive0.COALESCE(SUM(o.amount), 0) AS revenue_last_7d: when everyo.amountin a group isNULL(as for referrer77),SUMreturnsNULL;COALESCEconvertsNULLinto0.
SELECT p.referrer_user_id, -- Count unique referred users and unique buyers across the joined order rows COUNT(DISTINCT p.referred_user_id) AS referred_count, COUNT(DISTINCT o.user_id) AS buyers_last_7d, -- Replace NULL sum with 0 when a referrer has zero matching orders in the 7-day window COALESCE(SUM(o.amount), 0) AS revenue_last_7dTrace Example 1 row by row
In Example 1,
pairscollapses the 5 referral rows into 4 unique pairs:(10, 11),(10, 12),(11, 13), and(77, 14). AfterLEFT JOIN orderswith the window predicate insideON:referrer | referred | o.order_id | o.order_dt | o.user_id | o.amount ---------+----------+------------+------------+-----------+--------- 10 | 11 | 501 | 2025-08-28 | 11 | 40 10 | 11 | 502 | 2025-09-01 | 11 | 15 10 | 12 | NULL | NULL | NULL | NULL (08-25 filtered in ON) 11 | 13 | 504 | 2025-08-31 | 13 | 60 77 | 14 | NULL | NULL | NULL | NULLGrouping by
referrer_user_id:referrer_user_id | referred_count | buyers_last_7d | revenue_last_7d -----------------+------------------+------------------+------------------- 10 | 2 ({11, 12}) | 1 ({11}) | 40 + 15 = 55 11 | 1 ({13}) | 1 ({13}) | 60 77 | 1 ({14}) | 0 (ignores NULL) | COALESCE(NULL,0)=0Notice that referrer
77is absent fromusers— because our query readsreferralsandorderswithout an unnecessary join tousers, referrer77is preserved intact!Complete SQL query
Putting the
pairsCTE,LEFT JOIN ... ON, andGROUP BYtogether gives the complete solution:WITH pairs AS ( -- Deduplicate (referrer, referred) pairs first so duplicate referral logs never multiply order amounts SELECT DISTINCT referrer_user_id, referred_user_id FROM referrals ) SELECT p.referrer_user_id, -- Count unique referred users and unique buyers across the joined order rows COUNT(DISTINCT p.referred_user_id) AS referred_count, COUNT(DISTINCT o.user_id) AS buyers_last_7d, -- Replace NULL sum with 0 when a referrer has zero matching orders in the 7-day window COALESCE(SUM(o.amount), 0) AS revenue_last_7d FROM pairs AS p -- Filter order_dt inside ON (not WHERE) so referrers with no orders in the window keep their row LEFT JOIN orders AS o ON o.user_id = p.referred_user_id AND o.order_dt BETWEEN '2025-08-26' AND '2025-09-01' GROUP BY p.referrer_user_id✅ Submit now — all tests should pass.
Intuition & how it works
Imagine a program coordinator grading a roster of peer mentors (referrals) against a stack of bonus vouchers (orders) redeemed during the past week. Every mentor must appear on the summary sheet even if their mentees redeemed zero vouchers this week (LEFT JOIN). If you staple all historical vouchers ever redeemed onto the roster and then throw away every roster line lacking a voucher dated this week (WHERE), mentors whose mentees redeemed nothing this week get thrown in the trash! Instead, you restrict the voucher stack to this week while matching vouchers to mentees (ON), so mentors without recent vouchers remain on the sheet with 0 dollars. And before matching anything, you cross out duplicate mentor-mentee lines on the roster (SELECT DISTINCT) so a mentee listed twice never gets their voucher amounts added twice.
A naive query fails silently in two ways. First, placing WHERE o.order_dt BETWEEN '2025-08-26' AND '2025-09-01' after LEFT JOIN orders discards rows where o.order_dt is NULL (or earlier than August 26), converting the LEFT JOIN into an INNER JOIN — dropping referrer 77 completely and shrinking referrer 10's referred_count from 2 to 1! Second, joining raw referrals without deduplicating (referrer_user_id, referred_user_id) causes join fan-out (row multiplication when one user's orders match duplicate referral entries), doubling user 11's SUM(o.amount) from 55 to 110 while COUNT(DISTINCT ...) hides the bug in the counts.
Tracing Example 1 shows how every piece cooperates:
1. The pairs Common Table Expression (CTE) (a temporary named table defined with WITH) deduplicates (referrer_user_id, referred_user_id) into (10, 11), (10, 12), (11, 13), and (77, 14).
2. LEFT JOIN orders with o.order_dt BETWEEN '2025-08-26' AND '2025-09-01' inside ON attaches user 11's two window orders (40, 15), leaves NULLs on (10, 12) because order 503 occurred on '2025-08-25', attaches user 13's order (60), and leaves NULLs on (77, 14).
3. GROUP BY p.referrer_user_id applies COUNT(DISTINCT ...) and COALESCE(SUM(o.amount), 0) to return (10, 2, 1, 55), (11, 1, 1, 60), and (77, 1, 0, 0).
Complexity
Let R be the number of rows in referrals, P be the number of unique (referrer_user_id, referred_user_id) pairs (P <= R), O be the number of rows in orders, and J be the number of rows produced by the LEFT JOIN (J >= P).
- Time: O(R) expected with hashing (or O(R log R) with sorting) to materialize the P unique
pairs, followed by O(P + O + J) for a hash join againstorders(or O(P log O + J) with an index seek per referred user intoorders), plus O(J) expected time to group the J joined rows and maintain per-referrer hash sets forCOUNT(DISTINCT ...). - Space: O(P) memory to store the deduplicated
pairsCTE, plus up to O(P) memory across groups for the distinct user ID sets tracked during aggregation.
Indexes that help at scale:
- A composite covering index (an index containing every column read from that table so the engine never fetches heap rows) on orders(user_id, order_dt, amount) satisfies both ON predicates (user_id = ... and the order_dt range scan) directly from the index.
- A composite index on referrals(referrer_user_id, referred_user_id) allows sorted deduplication of pairs and sorted GROUP BY without an extra sort pass.
Edge cases
- Referrer with zero orders (or orders only prior to
'2025-08-26'): retained by keeping the date range insideONand wrappingSUM(o.amount)inCOALESCE(..., 0). - Duplicate referral rows across different
referral_dtdates (such as(10, 11)in Example 1): collapsed to one row inpairsbecausereferral_dtis omitted fromSELECT DISTINCT. - Separate orders with identical dollar amounts: summed accurately because we deduplicate
pairsprior to joining instead of writingSUM(DISTINCT o.amount). - One buyer placing multiple orders inside the window:
COUNT(DISTINCT o.user_id)counts the buyer once whileSUM(o.amount)adds all their orders;COUNT(DISTINCT p.referred_user_id)prevents multiple orders from inflatingreferred_count. - One user referred by two distinct referrers: counted under each referrer's row ("for every referrer"), though in finance reporting summing
revenue_last_7dacross referrers would double-attribute that user unless a first-touch attribution rule is enforced. - Referrer ID missing from
users(such as77in Example 1): preserved because our query readsreferralsandorderswithout an unnecessaryINNER JOINtousers. - Inclusive window endpoints (
'2025-08-26'and'2025-09-01'): both included byBETWEEN. Iforder_dtheld full timestamps ('2025-09-01 19:15:00'), use half-openo.order_dt >= '2025-08-26' AND o.order_dt < '2025-09-02'so evening orders on September 1 are included!
Common mistakes
- Putting
o.order_dt BETWEEN ...inWHEREinstead ofON: rejectsNULL-padded rows from unmatchedLEFT JOINs, dropping referrer77and lowering referrer10'sreferred_countfrom2to1on Example 1. - Joining raw
referralswithout deduplicating pairs first: multiplies user11's order revenue from55to110on Example 1 because(10, 11)is logged twice. - Using
SUM(DISTINCT o.amount)to mask fan-out: silently drops real revenue whenever two separate orders share the same price. - Writing
COUNT(o.user_id)orCOUNT(*)withoutDISTINCT: counts orders or joined rows instead of unique referred users and unique buyers (2buyers instead of1for referrer10when user11places two orders). - Omitting
COALESCE(..., 0)aroundSUM(o.amount): emitsNULLinstead of0for referrers without window orders.
Follow-up questions
- How do you list every referred user who placed zero orders on or before '2025-09-01' using a LEFT JOIN and HAVING without window functions?
LEFT JOINreferralstoorderswitho.order_dt <= '2025-09-01'insideON(so orders after'2025-09-01'are ignored without dropping the user),GROUP BY r.referred_user_id, r.referrer_user_id(which also collapses duplicate referral pairs), and filter withHAVING COUNT(o.order_id) = 0. Always count a non-nullable right-table column (COUNT(o.order_id)) rather thanCOUNT(*), becauseCOUNT(*)counts theNULL-padded row as1and would return zero rows! On Example 1, user12has an order on'2025-08-25' <= '2025-09-01', so only(14, 77)is returned.
sql
SELECT
r.referred_user_id,
r.referrer_user_id
FROM referrals AS r
LEFT JOIN orders AS 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
- How do you compute referred users, buyers, and conversion rate by country, and safely handle a stakeholder filter for 'UK' when ISO codes store 'GB'? Deduplicate
referred_user_idfirst,JOIN usersto attachcountry(excluding countries with0referred users), andLEFT JOIN orderswitho.order_dt <= '2025-09-01'insideONso zero-buyer countries stay with0buyers and0.0conversion (on Example 1:'DE','JP', and'US'each return1, 1, 1.0, while'GB'returns1, 0, 0.0). Before filtering to'UK', always inspectSELECT country, COUNT(*) FROM users GROUP BY country: SQL treats'UK'as a valid string literal that matches zero rows, silently returning0without any error! Confirming ISO 3166-1'GB'in the data lets you filterWHERE u.country = 'GB'safely.
```sql -- Step 1: Inspect actual country codes stored in users before filtering SELECT country, COUNT(*) AS n_users FROM users GROUP BY country ORDER BY country;
-- Step 2: Country-level conversion rate among referred users (filter WHERE u.country = 'GB' for UK) WITH referred AS ( SELECT DISTINCT referred_user_id AS user_id FROM referrals ) 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 referred AS r JOIN users AS u ON u.user_id = r.user_id LEFT JOIN orders AS o ON o.user_id = u.user_id AND o.order_dt <= '2025-09-01' GROUP BY u.country; ```
- If only the interviewer has database execution access, what two diagnostic queries would you ask them to run first before writing join logic? First, compare total row counts against distinct key counts across all three tables to spot duplicate primary keys or duplicate
(referrer_user_id, referred_user_id)rows (on Example 1,referralsshows5rows vs4unique pairs, immediately catching the fan-out hazard on(10, 11)). Second, check foreign-key coverage and date bounds onreferralsagainstusers— on Example 1,referrer_not_in_users = 1immediately surfaces orphan referrer77, proving before you write a line of join logic that inner-joininguserswould silently drop valid referrers!
```sql -- Diagnostic 1: Row counts vs. unique key counts to detect join fan-out risks SELECT 'users' AS table_name, COUNT() AS n_rows, COUNT(DISTINCT user_id) AS n_distinct_keys FROM users UNION ALL SELECT 'orders', COUNT(), COUNT(DISTINCT order_id) FROM orders UNION ALL SELECT 'referrals', COUNT(), (SELECT COUNT() FROM (SELECT DISTINCT referrer_user_id, referred_user_id FROM referrals)) FROM referrals;
-- Diagnostic 2: Orphan join keys in referrals and date bounds SELECT COUNT(*) AS referral_rows, SUM(CASE WHEN ref_u.user_id IS NULL THEN 1 ELSE 0 END) AS referrer_not_in_users, SUM(CASE WHEN new_u.user_id IS NULL THEN 1 ELSE 0 END) AS referred_not_in_users, MIN(r.referral_dt) AS first_referral_dt, MAX(r.referral_dt) AS last_referral_dt FROM referrals AS r LEFT JOIN users AS ref_u ON ref_u.user_id = r.referrer_user_id LEFT JOIN users AS new_u ON new_u.user_id = r.referred_user_id; ```
Follow-up questions
- How do you list every referred user who placed zero orders on or before '2025-09-01' using a LEFT JOIN and HAVING without window functions?
- How do you compute referred users, buyers, and conversion rate by country, and safely handle a stakeholder filter for 'UK' when ISO codes store 'GB'?
- If only the interviewer has database execution access, what two diagnostic queries would you ask them to run first before writing join logic?
Similar questions
- Reconstruct User Referral Graphs and Cycles
- Job Posting Engagement Metrics Excluding Non-Viewing Applicants
- Compute 7-Day DAU, D1 Retention, and Revenue Cohorts
- Class-Level 2024 Exam Summary with Zero-Filled Averages
- Summarizing Imaging Claims Spend and Fiscal Months
- Build Rolling User Features for Experiment Regression