Practice Free
EasyWindow Functions

Sequential Customer Order Indexing & First-Time Flag

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.

Solve in Workbench

Problem Statement

For each transaction in `customer_purchases`, use `ROW_NUMBER()` partitioned by `customer_id` and ordered by `order_time` ascending to calculate `order_sequence`. Include a boolean/text flag `is_first_order`: - `'YES'` if `order_sequence = 1` - `'NO'` otherwise Return: 1. `order_id` 2. `customer_id` 3. `order_time` 4. `amount` 5. `order_sequence` 6. `is_first_order` Order results by `customer_id` ascending, then by `order_sequence` ascending.

Why Technical Interviewers Ask This

Growth analytics pipelines index customer transaction streams chronologically to flag whether an order represents a new customer acquisition (Order #1) or repeat retention.

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 SQL
WITH numbered_orders AS (
        SELECT 
          order_id,
          customer_id,
          order_time,
          amount,
          ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY order_time ASC) AS order_sequence
        FROM customer_purchases
      )
      SELECT 
        order_id,
        customer_id,
        order_time,
        amount,
        order_sequence,
        CASE WHEN order_sequence = 1 THEN 'YES' ELSE 'NO' END AS is_first_order
      FROM numbered_orders
      ORDER BY customer_id ASC, order_sequence ASC;
Approach Breakdown
This query addresses the problem requirements by filtering and structuring data in Window Functions. It meets the target criteria: Customer orders indexed chronologically with first-time acquisition flag.

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.

More FAANG SQL Interview Questions

View all questions