MediumAggregations
Hospital Ward Inpatient Length of Stay & Bed Occupancy
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
Aggregate patient stays in the `ward_admissions` table grouped by `department_name`.
Calculate:
1. `department_name`
2. `total_admissions`: Count of all admissions
3. `avg_stay_days`: Average of `stay_duration_days` rounded to 1 decimal place
4. `max_stay_days`: Maximum `stay_duration_days` in that department
Only include departments that have **at least 2** admissions.
Order results by `avg_stay_days` descending.
Why Technical Interviewers Ask This
Hospital bed administration needs to optimize ward resource allocation. Operations wants a breakdown of inpatient stays grouped by medical department to identify wards with high patient turnover vs extended average length of stay (ALOS).
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 aggregations constructs.
Canonical Modern SQL Solution
PostgreSQL 16 / ANSI SQLSELECT
department_name,
COUNT(*) AS total_admissions,
ROUND(AVG(stay_duration_days), 1) AS avg_stay_days,
MAX(stay_duration_days) AS max_stay_days
FROM ward_admissions
GROUP BY department_name
HAVING COUNT(*) >= 2
ORDER BY avg_stay_days DESC;Approach Breakdown
This query addresses the problem requirements by filtering and structuring data in Aggregations. It meets the target criteria: Summary of department_name, total_admissions, avg_stay_days, and max_stay_days for wards with >= 2 admissions.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 Aggregations 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.