The Standing Fleet

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
L3
Asked in
Google

Problem

The on-call team is auditing our node fleet for machines that have dropped out of active service. Among the nodes marked draining or offline, count how many different machines are affected, counting a machine that appears under several node types only once.

Some hosts wear many hats. Count the machines, not the mentions.

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 1 of 1 rows
unique_hosts
4

Worked solution and explanation

What this really is

Beneath the audit story this is a filter-then-dedup. Narrow the fleet to the two out-of-service states, then count machines, not the rows that mention them. The catch is that this inventory lists every machine on many rows, once per node type and region, so COUNT(*) over the filtered rows counts entries and reports 68 where only 4 machines are actually affected. The other miss is paraphrasing the scope: status also holds 'Running', 'stopped' and 'STOPPED', so a filter written as status <> 'running' sweeps in parked and mis-cased rows and reports 10 machines.


Working through it

Step 1: Scope to the out-of-service states

WHERE status IN ('draining', 'offline') keeps only the machines that have left active service. Match the literals to the values stored in the column: these two states are each written in a single casing, so a mistyped 'Offline' or a status that isn't there would quietly match nothing.

Step 2: Count each machine once

COUNT(DISTINCT hostname) collapses the many inventory rows for one machine down to a single tally. This is the line that makes the answer 'how many machines' rather than 'how many rows', since every host appears once per node type and region.


The solution

Filter to the out-of-service states, then dedup
SELECT COUNT(DISTINCT hostname) AS unique_hosts
FROM infra_nodes
WHERE status IN ('draining', 'offline')

Common follow-up questions