Join customers to orders: return each ordering customers name and the days between their signupdate and their first…
SQLLevel: IntermediateDates and time
Join customers to orders: return each ordering customers name and the days between their signup_date and their first order (days_to_first).
Table definitions (from the source exercise):
CREATE TABLE customers(customer_id INTEGER PRIMARY KEY, name TEXT, city TEXT, signup_date TEXT, credit_score INTEGER);
CREATE TABLE orders(order_id INTEGER PRIMARY KEY, customer_id INTEGER, order_date TEXT, amount REAL, rep_id INTEGER, discount REAL);
Hints
- Write the join keys and relationship cardinality.
- What happens to duplicates and unmatched rows? Check WHERE versus ON.
Answer
Approach: MIN(order_date) per customer, DATEDIFF against signup_date.
SELECT c.name,
DATEDIFF(MIN(o.order_date), c.signup_date) AS days_to_first
FROM customers c
JOIN orders o ON o.customer_id = c.customer_id
GROUP BY c.customer_id, c.name, c.signup_date;
The source uses SQLite with a MySQL compatibility layer. Date and string functions are dialect dependent; the query is preserved as published.
Source and licence: SQL Practice Lab — Ebrahim Sharifi · MIT