Top Regions by High CPU Nodes

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
L5
Asked in
Yelp

Problem

We only have budget to add hardware in three regions this quarter, and a region's load is the total CPU percentage across all of its nodes in infra_nodes. Which three regions carry the heaviest load, heaviest first?

Five regions with the hottest CPUs.

Tables

infra_nodes

Columns: node_id INTEGER, hostname TEXT, region TEXT, node_type TEXT, cpu_pct REAL, mem_pct REAL, status TEXT

infra_nodes: 10 of 200 rows
node_idhostnameregionnode_typecpu_pctmem_pctstatus
1037web-02us-west-2memory1319stopped
1074api-01eu-west-1storage2638draining
1111api-02sa-east-1gpu3957offline
1148db-primaryeu-central-1general5276Running
1185db-replicaus-east-1compute6595STOPPED
1222cache-01us-west-2memory7814running
1259worker-01eu-west-1StorageNULLNULLstopped
1296worker-02ap-south-1gpu452draining
1333gpu-node-01eu-central-1general1771offline
1370WEB-03us-east-1compute3090Running

Expected output

First 3 of 3 rows
regiontotal_cpu_pct
us-east-11770
ap-south-11707
eu-west-11664

Worked solution and explanation

What this really is

This is a top-K over a grouped total wearing a capacity-planning badge. The fleet spans six regions and the budget covers three, so the whole question is: build one load figure per region, sort those figures, and cut at three. Everyone writes the SUM. What separates candidates is the order of operations: the cut has to land after the totals exist and after they are sorted. Cut early, or sort by something other than the total, and the hardware ships to the wrong regions.


Build it in order

Step 1: Collapse nodes to regions

GROUP BY region with SUM(cpu_pct) turns two hundred node rows into one row per region. Load is a quantity, so it is summed; a node count would reward a region stuffed with idle boxes.

Step 2: Sort the totals, heaviest first

ORDER BY total_cpu_pct DESC sorts on the alias, so the expression is written once. On this data the six totals are all different, so the order is fully determined and two correct answers cannot disagree.

Step 3: Keep three

LIMIT 3 runs last, after grouping and sorting. That is exactly why it is safe: it trims a sorted list of region totals, never raw rows. Drop it and you hand back all six regions for a three-region budget.

Three heaviest regions from `infra_nodes`
SELECT
    region,
    SUM(cpu_pct) AS total_cpu_pct
FROM infra_nodes
GROUP BY region
ORDER BY total_cpu_pct DESC
LIMIT 3

Group, sort on the total_cpu_pct alias, then cut with LIMIT 3.


Common follow-up questions