HardBusiness Analytics High Frequency
RFM (Recency, Frequency, Monetary) Customer Segmentation
Frequently Asked By:AmazonShopifyUber
Interactive In-Browser Workspace
Practice this problem on live schema tables in PostgreSQL 16 WASM with instant row verification and visual EXPLAIN plans.
Problem Statement
Group records in `ecom_transactions` by `customer_id`.
Calculate:
1. `customer_id`
2. `recency_days`: `DATE '2024-04-01' - MAX(order_date)`
3. `order_frequency`: `COUNT(*)`
4. `monetary_total`: `SUM(amount)`
Order results by `monetary_total` descending, then by `customer_id` ascending.
Why Technical Interviewers Ask This
E-commerce CRM marketing divides customers by RFM metrics: Recency (days between a reference audit date of '2024-04-01' and customer's latest order), Frequency (order count), and Monetary (total spend).
Common Pitfalls & Interview Traps
Forgetting required sorting and deterministic tie-breaking.
Not accounting for NULL or zero-value denominators during calculations.
Using inefficient quadratic subqueries instead of single-pass business analytics constructs.
Canonical Modern SQL Solution
PostgreSQL 16 / ANSI SQLSELECT
customer_id,
(DATE '2024-04-01' - MAX(order_date)) AS recency_days,
COUNT(*) AS order_frequency,
SUM(amount) AS monetary_total
FROM ecom_transactions
GROUP BY customer_id
ORDER BY monetary_total DESC, customer_id ASC;Approach Breakdown
This query addresses the problem requirements by filtering and structuring data in Business Analytics. It meets the target criteria: Customer profiles with Recency, Frequency, and Monetary metrics.Edge Cases to Verbally Clarify with Your Interviewer
The dataset contains zero matching records (must return valid empty result without crashing).
Multiple records tie on sorting criteria (must evaluate tie-breaking order deterministically).
Foreign keys or secondary attributes have NULL values.
Frequently Asked Follow-Up Questions
What makes this question a favorite among Amazon and Shopify interviewers?
Interviewers use this problem to test whether candidates write defensive, scalable Business Analytics queries that run efficiently on multi-million row production databases without excessive memory usage.
How does the query optimizer execute this query?
Using single-pass table scans with index lookups or sort buffers. Running EXPLAIN (ANALYZE, BUFFERS) in the DB Exercises workbench visualizes the execution nodes and buffer hit cache.