The Stable and the Restless

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
City and County of San Francisco

Problem

The reliability team is auditing pods that have never restarted. Break those down by status, showing how many fall into each, most common first.

Some pods never restart. That could mean anything.

Tables

k8s_pods

Columns: pod_id INTEGER, pod_name TEXT, nspace TEXT, status TEXT, restarts INTEGER, cpu_used REAL, mem_used REAL

k8s_pods: 10 of 200 rows
pod_idpod_namenspacestatusrestartscpu_usedmem_used
2043payment-003efproductionPending00.01137
2086search-003f6stagingCrashLoopBackOff00.02274
2129gateway-003fdmonitoringCompleted00.033111
2172worker-00404kube-systemError00.044148
2215cron-0040bdefaultTerminating00.055185
2258ml-serve-00412productionRunning0NULLNULL
2301cache-00419stagingPending00.077259
2344auth-00420monitoringCrashLoopBackOff00.088296
2387payment-00427kube-systemCompleted00.099333
2430search-0042edefaultError00.11370

Expected output

First 5 of 6 rows
statuspod_count
CrashLoopBackOff32
Pending32
Completed30
Error30
Terminating28

Worked solution and explanation

What this really is

This is a filtered frequency count wearing a Kubernetes costume. The real question: of the pods that have never restarted, how many sit in each lifecycle status? The skill being probed is scoping the population BEFORE you tally it. Restart count is a row filter (WHERE restarts = 0); status is the thing you bucket by. Candidates who blur those two group by restarts and hand back a histogram nobody asked for, or push the restart condition into HAVING and quietly drop the very buckets they were supposed to count.


Building it

Step 1: Scope to the survivors

WHERE restarts = 0 keeps only pods that have never restarted. It runs before any grouping, so it shrinks the population you are about to bucket. This is a per-row condition on a raw column, which is exactly what WHERE is for.

Step 2: Bucket by status

GROUP BY status collapses the survivors into one row per lifecycle status. With only five distinct statuses, the result is a compact, readable breakdown.

Step 3: Tally each bucket

COUNT(*) tallies the pods in each status group. Use * because you are counting pods, not the non-null values of some particular column.

Step 4: Most common first

ORDER BY pod_count DESC puts the busiest status on top. A secondary sort on status keeps equal counts in a stable, predictable order so the same query returns the same order every run.


The solution

Filtered status breakdown of never-restarted pods
SELECT status, COUNT(*) AS pod_count
FROM k8s_pods
WHERE restarts = 0
GROUP BY status
ORDER BY pod_count DESC, status

Common follow-up questions