Heavy Namespaces

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

Problem

A pod in k8s_pods only counts as failing when its status is 'Error' or 'CrashLoopBackOff', and the SRE team's cluster triage flags any namespace holding more than 12 failing pods. List the flagged namespaces with how many failing pods each one holds.

Kubernetes has favorites. Some namespaces carry more weight.

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 4 of 4 rows
nspacefailing_pods
default14
kube-system14
monitoring14
staging14

Worked solution and explanation

What this is really asking

This is a two-stage filter wearing a Kubernetes costume. A row-level filter, WHERE status IN ('Error', 'CrashLoopBackOff'), decides which pods count as failing; then, and only then, a group-level filter, HAVING COUNT(*) > 12, decides which namespaces made enough noise to report. The trap is collapsing the two stages: put the count in WHERE and the engine rejects it, drop the status filter and you count healthy pods too. Get either wrong and production, sitting at exactly 12 failing pods, slips into a list it does not belong on.


Break down the requirements

Step 1: Filter to failing pods first

WHERE status IN ('Error', 'CrashLoopBackOff') runs per row, before any grouping, so only failing pods survive to be counted. Skip it and COUNT(*) tallies every pod in the namespace, healthy ones included, and the whole answer shifts.

Step 2: Group and count

GROUP BY nspace collapses the survivors to one row per namespace, and COUNT(*) is now exactly the number of failing pods in each.

Step 3: Filter the groups

HAVING COUNT(*) > 12 keeps only the loud namespaces. WHERE cannot do this: the count does not exist until after GROUP BY. Alias it failing_pods so the result reads cleanly.


The solution

FAILING PODS BY NAMESPACE
SELECT nspace,
       COUNT(*) AS failing_pods
FROM k8s_pods
WHERE status IN ('Error', 'CrashLoopBackOff')
GROUP BY nspace
HAVING COUNT(*) > 12

COMMON FOLLOW-UP QUESTIONS

Common follow-up questions