Segment Customers by Recency, Frequency and Monetary Value (RFM)
Compute last order date, order count and spend per customer, then label each VIP, Regular, At-Risk or New.
The challenge runs on the SQLabHub practice database (SQLite) and uses the users and orders tables. You can solve it in the browser, with nothing to install.
The task
Segment customers by Recency (last order), Frequency (order count) and Monetary value. Label them as VIP, Regular, or At-Risk.
A correct answer returns 30 rows with 5 columns: name, last_order, frequency, monetary, segment.
Tables used in this challenge
users 150 rows
id INTEGER (PK) · first_name TEXT · last_name TEXT · email TEXT · phone TEXT · city TEXT · country TEXT · created_at TEXT · status TEXT · is_premium INTEGER
| id | first_name | last_name | phone | city | country | created_at | status | is_premium | |
|---|---|---|---|---|---|---|---|---|---|
orders 200 rows
id INTEGER (PK) · user_id INTEGER · total REAL · discount REAL · item_count INTEGER · status TEXT · order_date TEXT · shipped_date TEXT · shipping_city TEXT · shipping_country TEXT
| id | user_id | total | discount | item_count | status | order_date | shipped_date | shipping_city | shipping_country |
|---|---|---|---|---|---|---|---|---|---|
The first rows of each table are shown. See how all the tables relate on the database schema page.
Expected output
| name | last_order | frequency | monetary | segment |
|---|---|---|---|---|
First 5 of 30 rows. This is the output of the model solution on the practice database.
What you practise
- Summarising many rows into one value with COUNT, SUM, AVG, MIN or MAX
- Grouping rows with GROUP BY to get one result row per group
- Keeping every row of the left table with LEFT JOIN, matched or not
- Naming an intermediate result with a WITH clause and reading from it
- Turning conditions into values with CASE WHEN
- Building and cutting text values
- Sorting the result with ORDER BY
- Returning only the first rows with LIMIT
Hint and approach
Try the challenge first. Open these only when you need them.
Show the hint
Calculate R/F/M per user, then use CASE WHEN to classify
Show the step-by-step approach
How the model solution is built, in the order the database evaluates it:
- Define a common table expression named
rfm:- Read from the
userstable. - LEFT JOIN
ordersonorders.user_id=users.id, and only whereorders.statusis none of 'cancelled' or 'refunded'. Rows from the left side that have no match are kept, with NULL in the joined columns. - Group the rows by
users.id, so the result has one row for each value. - For each group, compute
MAX(orders.order_date),COUNT(orders.id)andSUM(orders.total). - Build
nameby joining text values with the||operator. ROUND()trims the calculated figures to a fixed number of decimals.
- Read from the
- Read from the
rfmCTE. - Label each row with a
CASEexpression (segment): the conditions are tested in order and the first one that is true decides the value. - Sort the result by
monetarydescending. - Keep only the first 30 rows with
LIMIT.
Model solution
Checking your session…
What to watch for
The status filter sits in the JOIN condition, not in WHERE. That keeps customers whose only orders were cancelled in the result with a frequency of 0; the same filter in WHERE would remove them. CASE returns the first branch that matches, so the order of the WHEN clauses decides the label.
- CTE (WITH). A CTE exists only for the single statement it is attached to. It is not a temporary table and cannot be reused by the next query.
- LEFT JOIN. A WHERE condition on the right-hand table removes the unmatched rows and turns the LEFT JOIN back into an inner join. Conditions on that table go in the ON clause.
- GROUP BY. Every selected column must either be in GROUP BY or sit inside an aggregate. SQLite accepts other columns and returns an arbitrary value for them; most databases raise an error.
Related SQL challenges
- Monthly Revenue Running Total with a CTE and Correlated SubquerySimilar levelHard
- Find the Week with the Highest RevenueSimilar levelHard
- Find the Top 15 Customers by Lifetime RevenueEasierMedium
- Find the Top 5 Customers by Total SpendEasierMedium
- Find the City with the Highest Total RevenueSimilar levelHard
Keep learning
- Lesson: CTEs (WITH Clause)
- Lesson: LEFT JOIN
- Lesson: GROUP BY
- Lesson: CASE WHEN
- All SQL practice challenges, by difficulty and topic
- SQL interview questions with answers
- SQL Playground: run any query on the same database