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:

  1. referrer_user_id: identifier of the referring user.
  2. referred_count: total number of distinct referred_user_id values linked to that referrer in referrals across all dates.
  3. buyers_last_7d: number of distinct referred users of that referrer who placed at least one order with order_dt between '2025-08-26' and '2025-09-01' inclusive.
  4. revenue_last_7d: sum of amount across orders placed by that referrer's referred users between '2025-08-26' and '2025-09-01' inclusive (0 when 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 ...), and SUM.
  • Both window endpoints '2025-08-26' and '2025-09-01' are inclusive.
  • If referrals is empty, return zero rows; if orders is empty, return every referrer from referrals with 0 buyers and 0 revenue.
  • Write standard SQL compatible with SQLite.

Step-by-step walkthrough

  1. 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 every referrer_user_id present in referrals:

    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 77 in Example 1) must still appear with 0 buyers and 0 revenue. 2. Never double-count duplicate referral rows: when (10, 11) appears twice in referrals, user 11's order revenue must still be summed only once. 3. No window functions allowed: solve using LEFT JOIN, COUNT(DISTINCT ...), SUM, and GROUP BY.

  2. Spot the two traps in a naive LEFT JOIN

    Most candidates begin with a draft that joins referrals directly to orders and places the date filter in WHERE:

    -- 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_id
    

    Why does this broken draft fail on Example 1? 1. WHERE silently destroys the LEFT JOIN: for referrer 77 (who referred user 14, with zero orders), LEFT JOIN produces a row where o.order_dt = NULL. Then WHERE runs after the join: NULL BETWEEN '2025-08-26' AND '2025-09-01' is not true, so SQL deletes referrer 77's row completely! Even worse, for (10, 12), user 12's only order is on '2025-08-25', so WHERE deletes (10, 12) and shrinks referrer 10's referred_count from 2 down to 1! 2. Duplicate referral rows multiply SUM(o.amount): in Example 1, (10, 11) appears on both '2025-08-18' and '2025-08-19', while user 11 placed orders of 40 and 15 (55 total). Joining raw referrals matches both orders twice (55 * 2 = 110). COUNT(DISTINCT ...) masks the duplicate in the counts while SUM(o.amount) silently doubles from 55 to 110!

    Let's fix one bug at a time.

  3. 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 collapse referrals first inside a Common Table Expression (CTE) — a temporary named table introduced with WITH:

    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_dt is excluded intentionally: in Example 1, (10, 11) was logged on both '2025-08-18' and '2025-08-19'. Keeping referral_dt would leave two rows for (10, 11) and still double user 11's order revenue. - Why SUM(DISTINCT o.amount) is NOT a valid fix: if user 11 placed two genuinely separate 20.00 orders (order_id 801 and 802), SUM(DISTINCT o.amount) would collapse them into 20.00 instead of 40.00! Deduplicating pairs before joining counts every real order once.

  4. Keep zero-order pairs by filtering dates in ON

    Next, we LEFT JOIN pairs to orders and place the 7-day date predicate inside ON, never in WHERE:

    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, and BETWEEN includes 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'
    
  5. Aggregate counts and revenue per referrer

    Finally, we GROUP BY p.referrer_user_id and compute all three metrics:

    • COUNT(DISTINCT p.referred_user_id) AS referred_count: even after deduplicating pairs, user 11 matches 2 orders in the window and produces 2 joined rows; DISTINCT ensures user 11 still counts as 1 referred user.
    • COUNT(DISTINCT o.user_id) AS buyers_last_7d: o.user_id is non-NULL only on rows where a window order matched. Because COUNT ignores NULLs and DISTINCT collapses repeat orders by user 11, referrers without window orders cleanly receive 0.
    • COALESCE(SUM(o.amount), 0) AS revenue_last_7d: when every o.amount in a group is NULL (as for referrer 77), SUM returns NULL; COALESCE converts NULL into 0.
    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
    
  6. Trace Example 1 row by row

    In Example 1, pairs collapses the 5 referral rows into 4 unique pairs: (10, 11), (10, 12), (11, 13), and (77, 14). After LEFT JOIN orders with the window predicate inside ON:

    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    |   NULL
    

    Grouping 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)=0
    

    Notice that referrer 77 is absent from users — because our query reads referrals and orders without an unnecessary join to users, referrer 77 is preserved intact!

  7. Complete SQL query

    Putting the pairs CTE, LEFT JOIN ... ON, and GROUP BY together 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 against orders (or O(P log O + J) with an index seek per referred user into orders), plus O(J) expected time to group the J joined rows and maintain per-referrer hash sets for COUNT(DISTINCT ...).
  • Space: O(P) memory to store the deduplicated pairs CTE, 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 inside ON and wrapping SUM(o.amount) in COALESCE(..., 0).
  • Duplicate referral rows across different referral_dt dates (such as (10, 11) in Example 1): collapsed to one row in pairs because referral_dt is omitted from SELECT DISTINCT.
  • Separate orders with identical dollar amounts: summed accurately because we deduplicate pairs prior to joining instead of writing SUM(DISTINCT o.amount).
  • One buyer placing multiple orders inside the window: COUNT(DISTINCT o.user_id) counts the buyer once while SUM(o.amount) adds all their orders; COUNT(DISTINCT p.referred_user_id) prevents multiple orders from inflating referred_count.
  • One user referred by two distinct referrers: counted under each referrer's row ("for every referrer"), though in finance reporting summing revenue_last_7d across referrers would double-attribute that user unless a first-touch attribution rule is enforced.
  • Referrer ID missing from users (such as 77 in Example 1): preserved because our query reads referrals and orders without an unnecessary INNER JOIN to users.
  • Inclusive window endpoints ('2025-08-26' and '2025-09-01'): both included by BETWEEN. If order_dt held full timestamps ('2025-09-01 19:15:00'), use half-open o.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 ... in WHERE instead of ON: rejects NULL-padded rows from unmatched LEFT JOINs, dropping referrer 77 and lowering referrer 10's referred_count from 2 to 1 on Example 1.
  • Joining raw referrals without deduplicating pairs first: multiplies user 11's order revenue from 55 to 110 on 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) or COUNT(*) without DISTINCT: counts orders or joined rows instead of unique referred users and unique buyers (2 buyers instead of 1 for referrer 10 when user 11 places two orders).
  • Omitting COALESCE(..., 0) around SUM(o.amount): emits NULL instead of 0 for 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 JOIN referrals to orders with o.order_dt <= '2025-09-01' inside ON (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 with HAVING COUNT(o.order_id) = 0. Always count a non-nullable right-table column (COUNT(o.order_id)) rather than COUNT(*), because COUNT(*) counts the NULL-padded row as 1 and would return zero rows! On Example 1, user 12 has 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_id first, JOIN users to attach country (excluding countries with 0 referred users), and LEFT JOIN orders with o.order_dt <= '2025-09-01' inside ON so zero-buyer countries stay with 0 buyers and 0.0 conversion (on Example 1: 'DE', 'JP', and 'US' each return 1, 1, 1.0, while 'GB' returns 1, 0, 0.0). Before filtering to 'UK', always inspect SELECT country, COUNT(*) FROM users GROUP BY country: SQL treats 'UK' as a valid string literal that matches zero rows, silently returning 0 without any error! Confirming ISO 3166-1 'GB' in the data lets you filter WHERE 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, referrals shows 5 rows vs 4 unique pairs, immediately catching the fan-out hazard on (10, 11)). Second, check foreign-key coverage and date bounds on referrals against users — on Example 1, referrer_not_in_users = 1 immediately surfaces orphan referrer 77, proving before you write a line of join logic that inner-joining users would 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

Similar questions

More Block (Square) interview questions

All 2 Block (Square) questions →