Customer Segmentation with CTEs
Part of the SQL Roadmap
In short
Marketing can't send one message to everyone. In this project you'll sort every customer into new, regular, high-value and at-risk groups with a chain of CTEs, then size each group in rupees.
Segment customers into groups such as new, regular, high-value and at-risk using a chain of CTEs that calculate order counts, total spend and days since last order.

Think of it like this
Grading mangoes at a Ratnagiri farm
At an Alphonso farm, each mango is first weighed and checked for ripeness. Then a simple rule card sorts it: big and ripe goes to the export crate, small but ripe to the local market, and soft ones to the pulp factory. Finally, the farmer counts each crate. Your CTE chain works the same way: measure each customer, apply rules, then count each group.
Watch it happen
Three named steps to a segment report
1/4Raw delivered orders: who bought, when, and for how much.
The big ideas
What you need to know
Measure, then label
Keep metrics and rules in separate CTEs. You can change a threshold without touching the maths.
Rule order matters
CASE stops at the first true WHEN. Put the most important segment, like At risk, first.
Write the rules down
Document each threshold, like 90 days or ₹25,000, so others can check and repeat the numbers.
Check each step
SELECT * FROM customer_metrics LIMIT 20 before moving on. Debug one CTE at a time.
How it works
Build the segmentation
- 1
Define the rules
Agree on what 'new', 'high value' and 'at risk' mean, in days and rupees.
- 2
Per-customer metrics
One CTE with orders, total spend, first and last order per customer.
- 3
Assign segments
A second CTE that applies the rules with CASE.
- 4
Summarise
Count customers and revenue per segment in the final SELECT.
- 5
Sanity check
Segment counts should add up to the total number of customers.
See it in code
Walk through the code
1WITH customer_metrics AS (2 SELECT customer_id,3 COUNT(*) AS orders,4 SUM(amount) AS total_spent,5 MIN(order_date) AS first_order,6 MAX(order_date) AS last_order7 FROM orders8 WHERE status = 'delivered'9 GROUP BY customer_id10),11segmented AS (12 SELECT customer_id, orders, total_spent,13 CASE14 WHEN CURRENT_DATE - last_order > 90 THEN 'At risk'15 WHEN total_spent >= 25000 THEN 'High value'16 WHEN first_order >= CURRENT_DATE - 30 THEN 'New'17 ELSE 'Regular'18 END AS segment19 FROM customer_metrics20)21SELECT segment,22 COUNT(*) AS customers,23 SUM(total_spent) AS revenue,24 ROUND(AVG(orders), 1) AS avg_orders25FROM segmented26GROUP BY segment27ORDER BY revenue DESC;1/3Step 1: one row per customer with the measurements the rules need.
The core query of the project. In PostgreSQL, subtracting two dates gives days. In MySQL use DATEDIFF(CURRENT_DATE, last_order), and in SQL Server DATEDIFF(day, last_order, GETDATE()).
Save yourself the pain
Common mistakes
Oops
Putting 'High value' before 'At risk' in the CASE.
Do this instead
A big spender who hasn't ordered in 6 months would be labelled High value and never get a win-back offer. Order rules by priority.
Oops
Hard-coding today's date like DATE '2026-11-24'.
Do this instead
Use CURRENT_DATE so the report stays correct next month, or one clearly named reference date in a CTE.
Oops
Customers with no delivered orders missing from the report.
Do this instead
They never reach customer_metrics. If you need them, start from customers and LEFT JOIN the metrics.
Your mission
Segment a real dataset
Quick check
A customer spent ₹40,000 but last ordered 120 days ago. With the CASE order in the code, which segment do they get?
Go deeper
- 1Build one CTE for per-customer metrics and a second that assigns a segment with CASE.
- 2Count customers and revenue per segment in the final SELECT.
- 3Document the rules for each segment so the numbers can be checked and repeated.
Stuck on this topic? Ask an Insider
Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.