Practice Free
HardWindow Functions High Frequency

Emergency Department Wait Time Quartiles with NTILE(4)

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.

Solve in Workbench

Problem Statement

For each emergency patient in `er_throughput`, assign a wait quartile from 1 to 4 based on `wait_minutes` ascending (Quartile 1 = shortest wait, Quartile 4 = longest wait). Return: 1. `patient_id` 2. `triage_acuity` 3. `wait_minutes` 4. `wait_quartile`: `NTILE(4) OVER (ORDER BY wait_minutes ASC)` Order results by `wait_minutes` ascending, then by `patient_id` ascending.

Why Technical Interviewers Ask This

Hospital quality assurance audits emergency department throughput. Patients are bucketed into wait-time quartiles to measure clinical delay across triage shifts.

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 window functions constructs.

Canonical Modern SQL Solution

PostgreSQL 16 / ANSI SQL
SELECT 
        patient_id,
        triage_acuity,
        wait_minutes,
        NTILE(4) OVER (ORDER BY wait_minutes ASC) AS wait_quartile
      FROM er_throughput
      ORDER BY wait_minutes ASC, patient_id ASC;
Approach Breakdown
This query addresses the problem requirements by filtering and structuring data in Window Functions. It meets the target criteria: ER patients categorized into 4 wait time quartiles.

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 Window Functions 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.

More FAANG SQL Interview Questions

View all questions