SQL interview question: find the bugs in a revenue query

MediumCode review

Problem

Shared data rules

The dashboard shows more revenue than the bank statement. For each city and platform, find revenue from successful September 2026 payments for delivered orders. Also give the platform’s share of the city’s revenue.

Formula

Query to fix

Fix it free
WITH city_revenue AS (
  SELECT city,
         SUM(amount_usd) AS city_revenue_usd
  FROM orders
  WHERE created_at >= '2026-09-01'
    AND created_at < '2026-10-01'
  GROUP BY city
)
SELECT o.city,
       o.platform,
       COUNT(*) AS orders,
       SUM(p.amount_usd) AS revenue_usd,
       ROUND(SUM(p.amount_usd)::numeric / MAX(cr.city_revenue_usd), 4) AS revenue_share
FROM payments AS p
JOIN orders AS o
  ON o.order_id = p.order_id
JOIN city_revenue AS cr
  ON cr.city = o.city
WHERE o.status = 'delivered'
  AND p.paid_at >= '2026-09-01'
  AND p.paid_at < '2026-10-01'
GROUP BY o.city, o.platform

Example

Input: orders
order_idcreated_atstatuscityplatformamount_usdRow note
8012026-09-05 09:40deliveredBostonios24
8022026-09-10 14:40deliveredBostonweb16
8032026-09-14 09:40cancelledBostonandroid30← not delivered — skipped
8042026-09-20 11:40deliveredNew Yorkios60
Input: payments
payment_idorder_idpaid_atamount_usdstatusRow note
18012026-09-05 10:0024failed← failed attempt — skipped
28012026-09-05 10:0124success
38022026-09-10 15:0016success
48032026-09-14 10:0030refunded← refund — skipped
58042026-09-20 12:0060success
Expected output
cityplatformordersrevenue_usdrevenue_share
Bostonios1240.6
Bostonweb1160.4
New Yorkios1601

Boston’s revenue is $24 + $16 = $40: ios gets 0.6 and web 0.4.

Output columns

orders
number of orders with a successful payment
Fix it free

Fix the query — code checks it on PostgreSQL in your browser. No sign-up needed.

Skills it tests

More interview questions

All questions