HardCTEs High Frequency
30-Day Hospital Readmission Rate Benchmark
Frequently Asked By:AppleGoogleAmazon
Interactive In-Browser Workspace
Practice this problem on live schema tables in PostgreSQL 16 WASM with instant row verification and visual EXPLAIN plans.
Problem Statement
Using a CTE, find all patients in `admissions_record` who were discharged and subsequently readmitted within 30 days.
Calculate:
1. `total_discharges`: Count of all discharge events
2. `readmissions_within_30d`: Count of readmissions occurring within 30 days of previous discharge
3. `readmission_rate_pct`: `ROUND(100.0 * readmissions_within_30d / total_discharges, 2)`
Return these three values in a single summary row.
Why Technical Interviewers Ask This
Federal health authorities track unplanned 30-day hospital readmissions. Clinical analysts use CTEs to measure what fraction of discharged patients were readmitted to the facility within 30 days.
Common Pitfalls & Interview Traps
Forgetting required sorting and deterministic tie-breaking.
Not accounting for NULL or zero-value denominators during calculations.
Using inefficient quadratic subqueries instead of single-pass ctes constructs.
Canonical Modern SQL Solution
PostgreSQL 16 / ANSI SQLWITH pairs AS (
SELECT
a1.stay_id,
a1.patient_id,
a1.discharge_date,
CASE
WHEN EXISTS (
SELECT 1 FROM admissions_record a2
WHERE a2.patient_id = a1.patient_id
AND a2.admission_date > a1.discharge_date
AND a2.admission_date <= a1.discharge_date + 30
) THEN 1 ELSE 0
END AS was_readmitted
FROM admissions_record a1
)
SELECT
COUNT(*) AS total_discharges,
SUM(was_readmitted) AS readmissions_within_30d,
ROUND(100.0 * SUM(was_readmitted) / COUNT(*), 2) AS readmission_rate_pct
FROM pairs;Approach Breakdown
This query addresses the problem requirements by filtering and structuring data in CTEs. It meets the target criteria: Single row summary showing total discharges, readmissions within 30 days, and readmission rate percentage.Edge Cases to Verbally Clarify with Your Interviewer
The dataset contains zero matching records (must return valid empty result without crashing).
Multiple records tie on sorting criteria (must evaluate tie-breaking order deterministically).
Foreign keys or secondary attributes have NULL values.
Frequently Asked Follow-Up Questions
What makes this question a favorite among Apple and Google interviewers?
Interviewers use this problem to test whether candidates write defensive, scalable CTEs queries that run efficiently on multi-million row production databases without excessive memory usage.
How does the query optimizer execute this query?
Using single-pass table scans with index lookups or sort buffers. Running EXPLAIN (ANALYZE, BUFFERS) in the DB Exercises workbench visualizes the execution nodes and buffer hit cache.