Date Operations & Time-Based Analytics SQL Topic exerciseMediumVerified answerSQLite + PostgreSQL + MySQL + SQL Server live · 1 guided

Customer First Order, Last Order, and Lifespan

Return one row per customer with first order, last order, lifespan days, and total orders.

  • Joins
  • Aggregation
  • Date analysis
  • Type conversion
  • Sorting

Exercise brief

Understand the request

Lifecycle marketing analyst Customer maturity reporting needs first order, last order, and observed purchasing lifespan.

Customer maturity reporting needs first order, last order, and observed purchasing lifespan. Return one row per customer with first order, last order, lifespan days, and total orders.

Return

  • Return customer_id, customer_name, first_order, last_order, lifespan_days, total_orders in this exact left-to-right order.

Constraints

  • Aggregate at customer grain.
  • Calculate lifespan from MAX(order_date) minus MIN(order_date).
  • Order by lifespan descending, then customer_id.

Data you will use

Review the relevant tables before deciding how to join, filter, or aggregate them.

customers

  • customer_idINTEGER
  • customer_nameTEXT

orders

  • order_idINTEGER
  • customer_idINTEGER
  • order_dateDATE

Hints, when you need them

Open one clue at a time so you still do the reasoning.

Hint 1

MIN(order_date) = first order; MAX(order_date) = last order, per customer.

Hint 2

lifespan_days = day-difference between the MAX and MIN order dates.

Hint 3

COUNT(*) within the group gives total orders.

Verified SQL answer

Attempt the problem first, then compare structure and reasoning—not just syntax.

Reveal solution and explanation
SELECT c.customer_id, c.customer_name, MIN(o.order_date) AS first_order, MAX(o.order_date) AS last_order, CAST(julianday(MAX(o.order_date)) - julianday(MIN(o.order_date)) AS INTEGER) AS lifespan_days, COUNT(*) AS total_orders FROM customers c JOIN orders o ON c.customer_id = o.customer_id GROUP BY c.customer_id, c.customer_name ORDER BY lifespan_days DESC, c.customer_id;

Why this works

Customer lifespan (first→last order span) is a key engagement metric. It combines MIN/MAX aggregation with a day-difference over those aggregates. The aggregation is identical everywhere; only the day-difference of the two aggregated dates differs by engine.

Success check

Every customer with orders appears once and single-day lifespans evaluate to zero.

Expected result

Use this output to verify values, aliases, ordering, and row count.

customer_idcustomer_namefirst_orderlast_orderlifespan_daystotal_orders
3Bob Williams2023-01-102024-08-055734
2Alice Johnson2023-02-152024-09-015645
1John Smith2024-01-152024-11-203105
5David Brown2024-04-102024-12-052393
4Carol Davis2024-03-152024-10-122113

Learn the concepts behind this answer

Strengthen your understanding with these targeted learning topics:

Continue practicing

SQL Practice Online

Open the interactive workspace and practice across SQL topics.