First Arrivals

A medium SQL interview practice problem on DataDriven. Write the query and run it against a real database, with instant feedback.

Domain
SQL
Difficulty
medium
Seniority
L5
Asked in
JPMorgan Chase

Problem

The transactions table holds one row per order, and a customer who keeps buying shows up on many dates while only their earliest order marks the day they arrived. Count how many customers placed their very first order on each date, oldest date first.

Every customer has a first day. Find when the crowds showed up.

Tables

transactions

Columns: transaction_id INTEGER, user_id INTEGER, transaction_date TEXT, product_id INTEGER, quantity INTEGER, total_amount REAL

transactions: 10 of 200 rows
transaction_iduser_idproduct_idquantitytotal_amounttransaction_date
10671971001223.462026-02-02
11342941050336.932026-03-03
12013911099450.42026-04-04
12684881148563.872026-05-05
13355851197002026-06-06
14026821246290.812026-07-07
146977912953104.282026-08-08
153687613444117.752026-09-09
160397313935-452026-01-10
1670107014421144.692026-02-11

Expected output

First 5 of 15 rows
first_datenew_customers
2022-01-021
2022-02-031
2022-03-241
2023-01-101
2023-02-031

Worked solution and explanation

What this really is

Beneath the acquisition-metrics costume, this is a per-customer earliest-date reduction feeding a per-date count: two aggregations at two different grains stacked back to back. Anyone can write a COUNT and a GROUP BY. The tell is whether you keep the grains straight: collapse each customer down to their first date first, THEN count those dates. Skip the first stage, group the raw table by date, and you count orders instead of first-time customers. Every repeat buyer then inflates the day they came back, and your 'new customer' curve is quietly a total-orders curve.


Walking it

Step 1: Find each customer's first transaction date

Reduce the raw table to one row per customer: MIN(transaction_date) grouped by user_id gives each customer's earliest order date. A customer who ordered five times still becomes a single row here, which is exactly what stops the later count from double-counting repeat buyers.

Step 2: Count new customers per day

Now the grain is one row per customer, stamped with their first date. Group THAT by first_date with COUNT(*) to tally how many customers debuted each day. The two GROUP BYs sit at different grains: customer, then date. Keep them in separate stages and the logic stays honest.


The solution

MIN date per user, then count per day
WITH first_purchase AS (
    SELECT user_id, MIN(transaction_date) AS first_date
    FROM transactions
    GROUP BY user_id
)
SELECT first_date, COUNT(*) AS new_customers
FROM first_purchase
GROUP BY first_date
ORDER BY first_date

Common follow-up questions