MediumAggregations
Net Realized Revenue & Promotional Discount Impact
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
Group records in `checkout_orders` by `promo_code`.
Calculate:
1. `promo_code`
2. `order_count`: Total orders using that code
3. `gross_sales`: Sum of `gross_amount`
4. `total_discount`: Sum of `discount_amount`
5. `net_revenue`: Difference between gross sales and discount (`SUM(gross_amount - discount_amount)`)
Filter using a `HAVING` clause to only keep promotions that generated at least **$500.00** in `net_revenue`.
Order results by `net_revenue` descending.
Why Technical Interviewers Ask This
Finance and growth marketing are evaluating coupon campaign ROI. They need a breakdown of sales grouped by discount promotion codes to verify which codes generate substantial net sales after deducting promotional price cuts.
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 aggregations constructs.
Canonical Modern SQL Solution
PostgreSQL 16 / ANSI SQLSELECT
promo_code,
COUNT(*) AS order_count,
SUM(gross_amount) AS gross_sales,
SUM(discount_amount) AS total_discount,
SUM(gross_amount - discount_amount) AS net_revenue
FROM checkout_orders
GROUP BY promo_code
HAVING SUM(gross_amount - discount_amount) >= 500.00
ORDER BY net_revenue DESC;Approach Breakdown
This query addresses the problem requirements by filtering and structuring data in Aggregations. It meets the target criteria: Summary of promo code sales metrics with net revenue >= $500, sorted by highest net revenue.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 Aggregations 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.