HardSQL challenge #192CTECASE WHENSegmentationBusiness Analytics

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.

Solve This SQL Challenge

Why this question comes up

RFM (recency, frequency, monetary) is a standard way for marketing teams to segment customers: when did they last buy, how often do they buy, how much do they spend. Each segment then gets a different campaign, for example a win-back offer for At-Risk customers.

The task

Segment customers by Recency (last order date), Frequency (order count) and Monetary value (total spent), ignoring cancelled and refunded orders. Label them VIP (5+ orders and 1,000+ spent), Regular (3+ orders or 500+ spent), At-Risk (no order since 2023 or no orders at all) or New. Show the 30 highest-spending customers.

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

First 3 rows of the users table
idfirst_namelast_nameemailphonecitycountrycreated_atstatusis_premium
1JenniferTorresjennifer.torres57@icloud.com+1-263-376-2371MontrealCanada2022-07-15active0
2DonnaAdamsdonna.adams52@gmail.com+1-753-780-6670CalgaryCanada2020-09-15inactive0
3KennethYoungkenneth.young94@proton.me+1-440-743-9503AustinUSA2023-09-05active0

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

First 3 rows of the orders table
iduser_idtotaldiscountitem_countstatusorder_dateshipped_dateshipping_cityshipping_country
143321.680.259cancelled2024-04-24NULLDelhiIndia
2810.520.191delivered2024-03-152024-03-20ColumbusUSA
3136181.190.085delivered2023-02-152023-02-18ChicagoUSA

The first rows of each table are shown. See how all the tables relate on the database schema page.

Expected output

Expected output of the challenge
namelast_orderfrequencymonetarysegment
Richard Harris2023-12-2315887.32Regular
Michael Carter2024-11-1533628.39Regular
Sharon Wright2023-03-0122832.03Regular
Laura Mitchell2024-12-1222765.92Regular
Amanda Davis2023-08-1822721.61Regular

First 5 of 30 rows. This is the output of the model solution on the practice database.

What you practise

  • Matching a column against a list of values with IN
  • 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:

  1. Define a common table expression named rfm:
    1. Read from the users table.
    2. LEFT JOIN orders on orders.user_id = users.id, and only where orders.status is none of 'cancelled' or 'refunded'. Rows from the left side that have no match are kept, with NULL in the joined columns.
    3. Group the rows by users.id, so the result has one row for each value.
    4. For each group, compute MAX(orders.order_date), COUNT(orders.id) and SUM(orders.total).
    5. Build name by joining text values with the || operator.
    6. ROUND() trims the calculated figures to a fixed number of decimals.
  2. Read from the rfm CTE.
  3. Label each row with a CASE expression (segment): the conditions are tested in order and the first one that is true decides the value.
  4. Sort the result by monetary descending.
  5. Keep only the first 30 rows with LIMIT.
Show the model solution
WITH rfm AS (
  SELECT u.id, u.first_name || ' ' || u.last_name AS name,
         MAX(o.order_date) AS last_order,
         COUNT(o.id) AS frequency,
         ROUND(SUM(o.total), 2) AS monetary
  FROM users u
  LEFT JOIN orders o ON o.user_id = u.id
    AND o.status NOT IN ('cancelled','refunded')
  GROUP BY u.id
)
SELECT name,
       last_order,
       frequency,
       monetary,
       CASE
         WHEN frequency >= 5 AND monetary >= 1000 THEN 'VIP'
         WHEN frequency >= 3 OR monetary >= 500 THEN 'Regular'
         WHEN last_order < '2023-01-01' OR frequency = 0 THEN 'At-Risk'
         ELSE 'New'
       END AS segment
FROM rfm
ORDER BY monetary DESC
LIMIT 30;

This query produced the expected output above. Yours does not have to match it word for word: any query that returns the same rows is correct.

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.
Solve This SQL Challenge

Keep learning