HardCTEs High Frequency
Customer Lifetime Value Decile 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
1. In a CTE `customer_ltv`, sum `total_spent` across all purchases in `ecom_orders` for each `customer_id`.
2. In the outer query, use `NTILE(4)` ordered by `lifetime_spend DESC` to assign an `ltv_quartile` (1 = top spenders, 4 = lowest spenders).
Return:
1. `customer_id`
2. `lifetime_spend`
3. `ltv_quartile`
Order results by `lifetime_spend` descending, then by `customer_id` ascending.
Why Technical Interviewers Ask This
E-commerce CRM marketing divides customers into 4 spend tiers (quartiles) to direct high-touch concierge support to the top 25% of spenders.
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 ctes constructs.
Canonical Modern SQL Solution
PostgreSQL 16 / ANSI SQLWITH customer_ltv AS (
SELECT
customer_id,
SUM(order_amount) AS lifetime_spend
FROM ecom_orders
GROUP BY customer_id
)
SELECT
customer_id,
lifetime_spend,
NTILE(4) OVER (ORDER BY lifetime_spend DESC) AS ltv_quartile
FROM customer_ltv
ORDER BY lifetime_spend DESC, customer_id ASC;Approach Breakdown
This query addresses the problem requirements by filtering and structuring data in CTEs. It meets the target criteria: Customer lifetime spend with quartile segmentation.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 CTEs 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.