Nodes by Region and Type

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

Domain
SQL
Difficulty
medium
Seniority
L3
Asked in
Apple

Problem

The capacity team is mapping fleet composition and needs node counts broken down by region and node type, listed alphabetically by region.

Broken down by region. Broken down by type.

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 5 of 7 rows
regionnode_typenode_count
ap-south-1gpu39
eu-central-1general40
eu-west-1Storage1
eu-west-1storage39
us-east-1compute40

Worked solution and explanation

What this is really asking

Strip the capacity-planning costume and this is a choice of grain: one count per (region, node_type) pair in infra_nodes. The trap is that the two columns almost move together on this data, roughly 40 nodes of one type per region, so a count keyed on either column alone looks right on five rows and quietly loses the two that are not. Everyone gets COUNT(*) right. What separates candidates is keying on the full pair and then pinning the alphabetical order the prompt asks for, because SQL hands back groups in no promised order.


Build it in three moves

Step 1: Group on the full grain

List both dimensions: GROUP BY region, node_type. On this seed that turns 200 rows into seven, one per pair that actually occurs. Key on region alone and eu-west-1's two stored values ('storage' and 'Storage') fold into one row. Key on node_type alone and the single 'sa-east-1' gpu node vanishes into one gpu total of 40. Neither mistake raises an error.

Step 2: Count every row

Use COUNT(*). Every node counts whatever its status, so there is no filter, and the NULLs in this table live in cpu_pct and mem_pct, which the count never reads. Counting rows is the simplest correct choice.

Step 3: Pin the ordering

Add ORDER BY region so the alphabetical requirement is enforced by the query, not left to chance. Only region order is promised: the two eu-west-1 rows may come back in either order.


The solution

Multi-column GROUP BY with explicit ordering
SELECT region, node_type, COUNT(*) AS node_count
FROM infra_nodes
GROUP BY region, node_type
ORDER BY region

One row per region-and-type pair, ordered alphabetically by region.


Common follow-up questions