Practice Free
HardCTEs High Frequency

Warehouse Inventory Stockout Risk & Reorder Priority

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

Write a query using a CTE to evaluate inventory health for each product in `warehouse_stock`: 1. In a CTE `velocity`, calculate: - `sku` - `current_stock` - `daily_sales_velocity`: `daily_sales` - `days_of_supply`: `ROUND(current_stock / daily_sales, 1)` 2. In the outer query, filter for products where `days_of_supply <= 10.0` (urgent replenishment risk). Return: 1. `sku` 2. `product_name` 3. `current_stock` 4. `days_of_supply` Order results by `days_of_supply` ascending, then by `sku` ascending.

Why Technical Interviewers Ask This

Warehouse fulfillment automated replenishment systems compare current available on-hand stock against 7-day average daily sales velocity to calculate estimated days of supply.

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 SQL
WITH stock_velocity AS (
        SELECT 
          sku,
          product_name,
          current_stock,
          ROUND(current_stock / daily_sales, 1) AS days_of_supply
        FROM warehouse_stock
      )
      SELECT 
        sku,
        product_name,
        current_stock,
        days_of_supply
      FROM stock_velocity
      WHERE days_of_supply <= 10.0
      ORDER BY days_of_supply ASC, sku ASC;
Approach Breakdown
This query addresses the problem requirements by filtering and structuring data in CTEs. It meets the target criteria: At-risk inventory items with 10 or fewer days of remaining stock.

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.

More FAANG SQL Interview Questions

View all questions