EasyFundamentals
Customer Loyalty Tier Classification with CASE WHEN
Frequently Asked By:AppleGoogleAmazon
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
Write a query to assign each customer in `loyalty_members` a loyalty tier based on `lifetime_spend`:
- `>= 5000.00` -> `'Platinum'`
- `>= 2000.00` -> `'Gold'`
- `>= 500.00` -> `'Silver'`
- Else -> `'Bronze'`
Alias the generated column as `tier_name`.
Return:
1. `member_id`
2. `first_name`
3. `last_name`
4. `lifetime_spend`
5. `tier_name`
Order results by `lifetime_spend` descending, then by `member_id` ascending.
Why Technical Interviewers Ask This
LuxeApparel is launching a VIP reward program. Marketing wants a segmented view of customer accounts categorizing their spend into loyalty tiers: 'Platinum' for $5,000+, 'Gold' for $2,000 - $4,999.99, 'Silver' for $500 - $1,999.99, and 'Bronze' for below $500.
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 fundamentals constructs.
Canonical Modern SQL Solution
PostgreSQL 16 / ANSI SQLSELECT
member_id,
first_name,
last_name,
lifetime_spend,
CASE
WHEN lifetime_spend >= 5000.00 THEN 'Platinum'
WHEN lifetime_spend >= 2000.00 THEN 'Gold'
WHEN lifetime_spend >= 500.00 THEN 'Silver'
ELSE 'Bronze'
END AS tier_name
FROM loyalty_members
ORDER BY lifetime_spend DESC, member_id ASC;Approach Breakdown
This query addresses the problem requirements by filtering and structuring data in Fundamentals. It meets the target criteria: Customer profiles with computed loyalty tier labels sorted by lifetime spend.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 Apple and Google interviewers?
Interviewers use this problem to test whether candidates write defensive, scalable Fundamentals 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.