Design an E-Commerce Top-Spender Query
Model a compact relational commerce dataset and design a correct, index-aware query for the ten highest-spending users in a trailing thirty-day window.
Problem statement
Design a relational data model for users, products, and orders, then find the ten users with the highest total recorded spend during the trailing thirty-day window.
For this exercise, an order exposes a globally unique order ID, its purchasing user ID, a directly comparable recorded spend amount, and a creation timestamp; these are the minimum authoritative inputs to the ranking query.
Products remain part of the modeled commerce schema, but product-level aggregation is outside the ranking contract. Evaluate the half-open window `[as_of - 30 days, as_of)`, rank users by summed recorded spend descending, and break equal totals by user ID ascending so the result is deterministic.
Explain the query plan and propose an index, including when the optimizer should use it and its write and storage costs.
The report supplies no row count, request rate, latency target, database engine, order lifecycle, refund policy, or currency-conversion rule, so state bounded workload assumptions and keep the index recommendation conditional on measured cardinality and plan evidence.
Payments, refunds, inventory, fulfillment, currency conversion, recommendation, and search flows are outside scope; treat the recorded amount as authoritative only for this exercise.
What to build
- Model users, products, and orders with stable identities, explicit relationships, and the minimum order fields required by the spender query.
- Define a half-open trailing thirty-day window and a deterministic top-ten ordering by total recorded spend and user ID.
- Return at most ten users with their summed recorded spend without counting an order outside the requested window or more than once.
- Inspect the query plan against bounded representative data and justify, measure, and safely roll out or reject a supporting index.
At scale
- The supported result contains at most ten users ranked over one trailing thirty-day half-open window.
- The source supplies no numeric table size, request rate, latency objective, or retention period; state a bounded workload assumption before choosing a physical design.
- Evaluate at least a selective recent window and a less-selective case so the index choice is supported by cardinality and measured plan evidence rather than assumed universally useful.
- Ordinary order writes continue while the index is introduced, so account for build impact, write amplification, storage, rollback, and stale optimizer statistics.