The Provinces

An easy SQL interview practice problem on DataDriven. Write the query and run it against a real database, with instant feedback.

Domain
SQL
Difficulty
easy
Seniority
mid
Asked in
Snap

Problem

We run a retail operation split into regional zones, with the US as our home base and main branch. Find the three highest earning zones outside the home region, biggest earners first.

The home office isn't the whole story. Find the zones carrying the rest.

Tables

orders

Columns: order_id INTEGER, status TEXT, region TEXT, profit REAL

orders: 10 of 200 rows
order_idstatusregionprofit
10097PendingEU69.37
10194CancelledAPAC88.74
10291ShippedLATAM108.11
10388ProcessingMEA127.48
10485ReturnedUS146.85
10582On HoldEU166.22
10679CompletedAPAC185.59
10776PendingLATAM204.96
10873CancelledMEA224.33
10970ShippedUS243.7

Expected output

First 3 of 3 rows
regiontotal_profit
APAC27668.88
EU26959.64
LATAM26911.32

Worked solution and explanation

What this problem is really testing

This is a top-three-after-exclusion dressed up as a regional earnings report. The skill being probed: do you drop the home region BEFORE you rank, or after? Anyone can sum profit per region. The tell is whether the filter that removes the main branch runs on the base rows, ahead of the ordering and the LIMIT. Rank first and slice off the top three and you either hand back the US home region you were told to exclude, or you silently bump a real zone off the bottom of the list.


Break down the requirements

Step 1: Exclude the home region on the base rows

'US as our home base and main branch' is a filter on region, not a row you remove after aggregating. Put WHERE region <> 'US' before the grouping so US profit never enters any bucket.

Step 2: Roll up to the zone grain

GROUP BY region and SUM(profit). The question is about zones, so one row per region is the unit. Note profit can be negative on returns, so SUM (not COUNT) is the earning measure.

Step 3: Order high to low, then take three

ORDER BY total_profit DESC puts the biggest earners on top, and LIMIT 3 keeps the leaderboard short. The DESC has to sit on the summed total, not on raw profit.


The solution

TOP EARNING ZONES OUTSIDE HOME
SELECT region,
       SUM(profit) AS total_profit
FROM orders
WHERE region <> 'US'
GROUP BY region
ORDER BY total_profit DESC
LIMIT 3
Exclude after ranking (wrong)
Sum every region including US, sort, take the top three, then try to drop US. If US is the biggest earner it was inside your top three, so you return two real zones plus a hole, or you keep US entirely.
Exclude before ranking (right)
WHERE region <> 'US' removes the home region from the base rows, so the aggregate, the sort, and the LIMIT all operate only on the zones you actually want. The top three are three genuine outside zones.

Common follow-up questions