HardWindow Functions High Frequency
Customer Initial vs Recent Order with FIRST_VALUE()
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
For each customer order in `customer_purchases`, determine the customer's first-ever order amount using `FIRST_VALUE()`.
Return:
1. `order_id`
2. `customer_id`
3. `order_date`
4. `order_amount`
5. `initial_order_amount`: `FIRST_VALUE(order_amount) OVER (PARTITION BY customer_id ORDER BY order_date ASC)`
Order results by `customer_id` ascending, then by `order_date` ascending.
Why Technical Interviewers Ask This
CRM retention teams want to analyze order size expansion over customer lifecycles by contrasting the customer's initial purchase against subsequent orders.
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 window functions constructs.
Canonical Modern SQL Solution
PostgreSQL 16 / ANSI SQLSELECT
order_id,
customer_id,
order_date,
order_amount,
FIRST_VALUE(order_amount) OVER (PARTITION BY customer_id ORDER BY order_date ASC) AS initial_order_amount
FROM customer_purchases
ORDER BY customer_id ASC, order_date ASC;Approach Breakdown
This query addresses the problem requirements by filtering and structuring data in Window Functions. It meets the target criteria: Order history showing order amount alongside the customer first purchase value.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 Window Functions 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.