Interview's MateSQL Learning
Interview's Mate

SQL Learning

Foundations → production SQL

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
SQL topics
Lesson 95/ 160
05. Window Functions & Analytical SQL

Finding User First Purchase, Repeat Purchase & Time-Between-Orders

Identify first/repeat purchases and measure days between orders.

IntermediateFirst Purchase · Repeat3 quiz questions
Practice SQL
In plain wordsDiagramExamples & theoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

In plain words

Number each customer's orders in date order; number 1 is their first purchase, the rest are repeats.

Think of it like…

A café's loyalty card: the first stamp marks the first visit, every later stamp is a repeat visit, and the dates between stamps show how often someone comes back.

Where you’ve seen it

A D2C skincare brand asks: "Of customers whose first order was in Q1, what share ordered again within 90 days, and what's the median time to the second order?" The query numbers valid orders per customer, takes order 1 and order 2, keeps customers whose first order is at least 90 days old, and reports a 31% repeat rate with a median of 38 days to the second order.

Words you’ll hear

Order number
ROW_NUMBER over each customer's orders by date; 1 = first purchase.
Repeat purchase rate
Customers with a second order ÷ customers with a first order, in a fixed window.
Inter-order time
Days between consecutive orders, from LAG or LEAD.
Right-censoring
Recent customers haven't had time to repeat yet, which biases rates downward.

Visual diagram

Loading interactive diagram

Theory & example queries

Numbering orders and measuring gaps

Filter to orders that count first: paid, not cancelled or fully refunded, not test accounts. Then number them per customer by time with a tie-breaker, and add LAG(created_at) OVER (PARTITION BY customer_id ORDER BY created_at, order_id) for the previous order's time. Days between orders is the difference, which is NULL for each customer's first order.

Those columns answer several questions directly. New vs returning revenue per month: SUM(amount) FILTER (WHERE order_number = 1) and FILTER (WHERE order_number > 1). Typical purchase cycle: PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY days_since_prev) over repeat orders. Customers who bought exactly once: order count = 1. Decide up front whether two orders on the same day are one purchase occasion or two.

Numbered ordersQuery example
1Input dataStart from the source rows or state that the statement sees.
orders
3 rows
orders sample rows
idcustomer_idstatusamountcoupon_code
1011paid249NULL
1022paid120WELCOME10
1031shipped89.5NULL
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1WITH2  valid AS (3    SELECT4      *5    FROM6      orders7    WHERE8      status = 'paid'9      AND NOT is_test10  ),11  numbered AS (12    SELECT13      customer_id,14      order_id,15      created_at,16      amount,17      ROW_NUMBER() OVER w AS order_number,18      created_at::date - LAG(created_at::date) OVER w AS days_since_prev19    FROM20      valid21    WINDOW22      w AS (23        PARTITION BY24          customer_id25        ORDER BY26          created_at,27          order_id28      )29  )30SELECT31  *32FROM33  numbered;
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · SQL expression

Read this line together with the surrounding statement as part of the same SQL expression.

1/33
3OutputInspect the representative rows, affected-row count, plan, or command status.
Expected output4 sample rows
Expected output
customer_idorder_idcreated_atamountorder_numberdays_since_prev
425012026-01-05 09:00:004501NULL
425202026-03-12 11:30:00800266
775122026-02-01 15:00:001201NULL
775402026-05-01 10:15:00360289

Note: Illustrative valid, paid, non-test orders numbered within each customer.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

Key takeaway: Filter valid orders, ROW_NUMBER for position, LAG for the gap.

A fair repeat purchase rate

"Share of customers who ever ordered twice" punishes recent customers, who haven't had time to come back, so the rate seems to fall as the business grows. Use a fixed window from the first order, such as "second order within 90 days", and include only customers whose first order is at least 90 days before the data's end. Report it by first-order month so cohorts can be compared.

Pivot the first two orders per customer with conditional aggregation: MIN(created_at) FILTER (WHERE order_number = 1) and FILTER (WHERE order_number = 2). Then the repeat flag is second_at <= first_at + interval '90 days', and time to second order is their difference. Keep customers without a second order in the denominator; they're the ones who didn't come back.

90-day repeat rate by first-order monthQuery example
1Input dataStart from the source rows or state that the statement sees.
This statement works with the current schema, configuration, or database state rather than a row dataset. The command still follows the same input → query → result flow.
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1WITH2  firsts AS (3    SELECT4      customer_id,5      MIN(created_at) FILTER (6        WHERE7          order_number = 18      ) AS first_at,9      MIN(created_at) FILTER (10        WHERE11          order_number = 212      ) AS second_at13    FROM14      numbered15    GROUP BY16      customer_id17  )18SELECT19  date_trunc('month', first_at) AS cohort,20  COUNT(*) AS customers,21  ROUND(22    100.0 * COUNT(*) FILTER (23      WHERE24        second_at <= first_at + interval '90 days'25    ) / COUNT(*),26    127  ) AS repeat_90d_pct28FROM29  firsts30WHERE31  first_at <= now() - interval '90 days'32GROUP BY33  134ORDER BY35  1;
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · SQL expression

Read this line together with the surrounding statement as part of the same SQL expression.

1/35
3OutputInspect the representative rows, affected-row count, plan, or command status.
Expected output3 sample rows
Expected output
cohortcustomersrepeat_90d_pct
2026-01-0152031.5
2026-02-0161034.1
2026-03-0157529.7

Note: Illustrative mature cohorts whose first orders are at least 90 days old relative to the sample execution date.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

Key takeaway: Fixed window from first order, only mature cohorts, non-repeaters in the denominator.

Interactive walkthrough

How it works, step by step

Follow one practical SQL workflow from start to finish. Select any step or play through the flow.

Progress1/4
Step 1Definition

Define a valid order

Exclude cancelled, fully refunded and test orders, and decide how to treat same-day orders.

Focus at this step

status = 'paid' AND NOT is_test

What to watch at this step
Write it
down
Tip: use ← → to move between steps

When to use it & trade-offs

What it is

Purchase-behaviour metrics start by numbering each customer's orders: ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY created_at, order_id). Order 1 is the first purchase, order 2 or later is a repeat purchase, and created_at - LAG(created_at) gives the time between orders. From those columns come the repeat purchase rate, time to second order, and new versus returning revenue.

Why it matters: Repeat customers drive most of the profit in e-commerce, subscriptions and food delivery, so growth teams track "what share of first-time buyers come back, and how fast?" constantly. Interviewers use these questions because they combine window functions with careful definitions: which orders count, and how to be fair to customers who only bought recently.

When to reach for it

  • Repeat rate and time-to-second-order dashboards
  • New vs returning revenue reports
  • Timing retention emails

When to avoid or be careful

  • "Ever repeated" rates compared across months
  • Counting refunded or test orders
  • Dropping one-time buyers from the denominator

Ways to measure repeat purchasing

Repeat within N days of first order
Best for: Comparing cohorts and tracking trends

Strengths: Fair across old and new customers.

Watch out: Recent cohorts can't be reported until N days pass.

Ever repeated
Best for: A quick lifetime snapshot

Strengths: Simple to compute.

Watch out: Biased against recent customers; falls as you grow.

Median days between orders
Best for: Planning reminder emails and replenishment

Strengths: Describes the purchase cycle directly.

Watch out: Says nothing about customers who never return.

Interview signals & numbers to know

When this topic comes up

  • “What percentage of customers buy again?”
  • “Average time between orders”
  • “Revenue from new vs returning customers”
  • Customer lifecycle metrics
  • E-commerce analytics

Benchmarks & rules of thumb

1 -
order_number of a first purchase
90 days -
a common repeat window
NULL -
days_since_prev on each customer's first order

Common mistakes & follow-ups

Common interview mistakes

  • Computing repeat rate over all customers including last week's first-time buyers, making it look like retention is collapsing.
  • Ordering by created_at alone, so two orders at the same second swap first and second between runs.
  • Using AVG days between orders, which a few customers with year-long gaps pull far above the typical cycle.

Likely interviewer follow-ups

  • How would you calculate a 90-day repeat purchase rate by month of first order?
  • How do you split monthly revenue into new and returning customers?
  • Why use the median rather than the average time between orders?
Interview tip: Before writing SQL, state the valid-order definition and the repeat window. Defining the metric carefully is what interviewers are really testing here.

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply Finding User First Purchase, Repeat Purchase & Time-Between-Orders with hands-on SQL practice and interview Q&A.

Open SQL Practice →SQL interview Q&A
Previous topic
Year-over-Year (YoY), Month-over-Month (MoM) & Day-over-Day Growth
Next topic
Streak Detection & Consecutive Day Login Queries