Daily and Category-Level New Customer Purchase Rate
SQL & DataModel answerLast updated
Flag each order as a customer's first in a category or overall, then aggregate to compute new-buyer proportions by day and category.
Daily and Category-Level New Customer Purchase Rate
You work on the analytics team for an e-commerce platform. Leadership wants to understand how much of each day's order volume comes from customers making their very first purchase — both within a specific product category and across the platform as a whole.
You have access to an orders table:
+----------+------------+----------+-------------+
| order_id | date | category | customer_id |
+----------+------------+----------+-------------+
| 100 | 2025-01-01 | Books | 1 |
| 101 | 2025-01-02 | Books | 1 |
| 102 | 2025-01-01 | Music | 2 |
| 103 | 2025-01-03 | Music | 3 |
| 104 | 2025-01-03 | Books | 2 |
+----------+------------+----------+-------------+
Columns:
order_id— unique identifier for each order; higher values indicate later placement when orders fall on the same daydate— calendar date of the order (day granularity)category— product category of the ordercustomer_id— identifier for the purchasing customer
What to compute
Metric 1 — by day and category: For every (date, category) pair, what proportion of orders in that group represent the placing customer's first-ever order in that category?
Metric 2 — by day: For every calendar day, what proportion of that day's orders represent a customer's first order across any category?
Expected output
Metric 1:
+------------+----------+--------------+-------------+-------------------------+
| date | category | total_orders | first_orders| first_order_proportion |
+------------+----------+--------------+-------------+-------------------------+
| 2025-01-01 | Books | 1 | 1 | 1.0 |
| 2025-01-01 | Music | 1 | 1 | 1.0 |
| 2025-01-02 | Books | 1 | 0 | 0.0 |
| 2025-01-03 | Books | 1 | 1 | 1.0 |
| 2025-01-03 | Music | 1 | 1 | 1.0 |
+------------+----------+--------------+-------------+-------------------------+
Metric 2:
+------------+--------------+-------------+------------------------+
| date | total_orders | first_orders | first_order_proportion |
+------------+--------------+-------------+------------------------+
| 2025-01-01 | 2 | 2 | 1.0 |
| 2025-01-02 | 1 | 0 | 0.0 |
| 2025-01-03 | 2 | 1 | 0.5 |
+------------+--------------+-------------+------------------------+
Requirements and assumptions
- "First order in a category" means the chronologically earliest order for that customer in that category, based on the full history of the table — not just the current reporting window.
- "First order overall" means the chronologically earliest order for that customer across all categories.
- When two orders from the same customer fall on the same date, use
order_idas a tie-breaker (lower ID = earlier). - The proportion denominator is total orders in the group, not total customers.
- You may write your solution in SQL, Python (pandas), or both.
Hints
Hint 1
Start by assigning each order a rank within its partition before doing any grouping. For Metric 1 the partition is (customer_id, category); for Metric 2 it is customer_id alone. A rank of 1 means it is the first order in that partition.
Hint 2
Once you have a 0/1 flag column, the proportion is just the mean of that flag within the reporting group. This avoids writing a separate numerator subquery and a denominator subquery and then joining them.
Hint 3
Watch out for two classic traps: same-day ties (use order_id as a secondary sort key, not just date) and computing flags after filtering to a date range (a customer who bought last year will look like a new customer if you exclude that history before flagging).
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach: Flag First, Then Aggregate
This problem has two distinct steps. Resist the urge to jump straight to grouping — the right move is to annotate every row with first-order flags first, then aggregate.
Clarify definitions before writing anything
A strong answer starts by pinning down ambiguities:
- First in category: the single earliest order for a given
(customer_id, category)pair, evaluated over the entire table history, not just the visible date range. - First overall: the single earliest order for a given
customer_idacross all categories. - Tie-breaking:
dateis day-level, so two orders on the same day need a secondary key. Lowerorder_id= earlier, per the problem statement. If a real timestamp were available, use that instead. - Denominator: all orders in the group, not unique customers. A customer who places three orders today contributes three rows to the denominator.
Why window functions beat self-joins here
A self-join approach (JOIN (SELECT customer_id, MIN(date) FROM orders GROUP BY customer_id)) breaks as soon as two orders share a date. You then need a nested subquery to also take MIN(order_id) within that date, which is awkward. ROW_NUMBER() with a two-column ORDER BY handles ties cleanly in one pass.
Worked example — the revealing row
Order 104 illustrates why the two flags need different partitions:
| order_id | date | category | customer | first_in_cat | first_overall |
|---|---|---|---|---|---|
| 100 | 01-01 | Books | 1 | 1 | 1 |
| 102 | 01-01 | Music | 2 | 1 | 1 |
| 101 | 01-02 | Books | 1 | 0 | 0 |
| 104 | 01-03 | Books | 2 | 1 | 0 |
| 103 | 01-03 | Music | 3 | 1 | 1 |
Order 104 is customer 2's first Books purchase (first_in_cat = 1) but not their first purchase overall — that was order 102 in Music (first_overall = 0). This is why Metric 2 for 2025-01-03 is 0.5: one of the two orders on that day is a platform-first.
SQL solution
WITH flagged AS (
SELECT
order_id,
date,
category,
customer_id,
CASE
WHEN ROW_NUMBER() OVER (
PARTITION BY customer_id, category
ORDER BY date, order_id
) = 1 THEN 1 ELSE 0
END AS is_first_in_category,
CASE
WHEN ROW_NUMBER() OVER (
PARTITION BY customer_id
ORDER BY date, order_id
) = 1 THEN 1 ELSE 0
END AS is_first_overall
FROM orders
)
-- Metric 1: proportion by day and category
SELECT
date,
category,
COUNT(*) AS total_orders,
SUM(is_first_in_category) AS first_orders,
AVG(is_first_in_category * 1.0) AS first_order_proportion
FROM flagged
GROUP BY date, category
ORDER BY date, category;
-- Metric 2: proportion by day
-- SELECT
-- date,
-- COUNT(*) AS total_orders,
-- SUM(is_first_overall) AS first_orders,
-- AVG(is_first_overall * 1.0) AS first_order_proportion
-- FROM flagged
-- GROUP BY date
-- ORDER BY date;
Note the * 1.0 in the AVG. In PostgreSQL, SQL Server, and SQLite, AVG over an integer column performs integer division and silently returns 0 for proportions less than 1. Interviewers specifically look for this.
Python (pandas) solution
import pandas as pd
def new_buyer_proportions(
orders: pd.DataFrame,
) -> tuple[pd.DataFrame, pd.DataFrame]:
"""
Parameters
----------
orders : DataFrame with columns
[order_id, date, category, customer_id]
Returns
-------
by_day_category : first-order proportion per (date, category)
by_day : first-order proportion per date
"""
df = orders.copy()
df["date"] = pd.to_datetime(df["date"])
# Sort so that earlier orders come first; order_id breaks same-day ties.
df = df.sort_values(["date", "order_id"], kind="mergesort")
# cumcount() within each group starts at 0 for the first row.
df["is_first_in_category"] = (
df.groupby(["customer_id", "category"])
.cumcount()
.eq(0)
.astype(int)
)
df["is_first_overall"] = (
df.groupby("customer_id")
.cumcount()
.eq(0)
.astype(int)
)
by_day_category = (
df.groupby(["date", "category"])
.agg(
total_orders=("order_id", "size"),
first_orders=("is_first_in_category", "sum"),
first_order_proportion=("is_first_in_category", "mean"),
)
.reset_index()
)
by_day = (
df.groupby("date")
.agg(
total_orders=("order_id", "size"),
first_orders=("is_first_overall", "sum"),
first_order_proportion=("is_first_overall", "mean"),
)
.reset_index()
)
return by_day_category, by_day
Complexity
- Time: O(n log n) — dominated by the sort (or the internal sort inside each window function). Aggregation is O(n) with hash grouping.
- Space: O(n) for the flag columns; output is O(D × C) for Metric 1 and O(D) for Metric 2, where D = distinct days and C = distinct categories.
Edge cases and common mistakes
Filtering before flagging. If a report only covers January but the table has prior history, applying a WHERE date >= '2025-01-01' before the window function makes returning customers look like new ones. Always compute flags on the full history, then filter the aggregation output.
Same-day ties without a tie-breaker. Using RANK() or a MIN(date) self-join without also handling order_id can assign rank 1 to two rows from the same customer on the same day. ROW_NUMBER() with ORDER BY date, order_id guarantees exactly one row gets rank 1.
Integer division in SQL. Already mentioned above — cast to a float before dividing or using AVG.
NULL customer_id (guest checkout). With PARTITION BY, all NULL customer IDs fall into one partition, so the second guest order in any category would be flagged as non-first despite being from a different person entirely. The right call is to either exclude NULLs or treat each guest order as its own first order, depending on business rules — but you should name this assumption explicitly.
Duplicate order_id rows. Deduplicate on order_id before running the flags to avoid double-counting.