Interview Questions/SQL/First Purchase per Customer with Days-to-Convert

First Purchase per Customer with Days-to-Convert

Preview mode. Log in to edit, run, submit, and save progress.

Medium

Description

You have two tables: Customers (with a registration date) and Orders (with purchase amounts and dates). A customer may place multiple orders. Write a SQL query to return, for each customer who has placed at least one order: their customer_id, name, the date of their first order, the amount of that first order, and the number of days between registration and first order (days_to_first_order). Customers with no orders should NOT appear in the result. Return results ordered by customer_id. Tables: Customers, Orders Customers:

Column NameTypeDescription
idINTPrimary key
nameVARCHARCustomer name
registered_dateDATEAccount registration date

Orders:

Column NameTypeDescription
idINTPrimary key
customer_idINTFK to Customers.id
amountINTOrder amount
order_dateDATEDate order was placed

Database Schema (Inferred)

Customers

Column NameExample Value
id1
nameAlice
registered_date2023-01-01

Orders

Column NameExample Value
id1
customer_id1
amount250
order_date2023-01-10

Example

Customers

idnameregistered_date
1Alice2023-01-01
2Bob2023-02-15
3Carol2023-03-01

Orders

idcustomer_idamountorder_date
112502023-01-10
211002023-01-20
324002023-03-01
42502023-04-05
533002023-05-20

Output

customer_idnamefirst_order_datefirst_amountdays_to_first_order
1Alice2023-01-102509
2Bob2023-03-0140014
3Carol2023-05-2030080

Explanation:

Use a CTE to find MIN(order_date) per customer_id, then join back to get the amount for that date, then JOIN with Customers to compute julianday difference.

Approach hint

Start with a simple approach, explain the trade-off, then move toward a cleaner or more scalable solution.

Common mistake

Skipping assumptions, edge cases, or trade-offs can make an otherwise good answer feel incomplete.

SQL Editor
Loading...

Customers

idnameregistered_date
1Alice2023-01-01
2Bob2023-02-15
3Carol2023-03-01

Orders

idcustomer_idamountorder_date
112502023-01-10
211002023-01-20
324002023-03-01
42502023-04-05
533002023-05-20

Output

customer_idnamefirst_order_datefirst_amountdays_to_first_order
1Alice2023-01-102509
2Bob2023-03-0140014
3Carol2023-05-2030080