Practice Free
MediumWindow Functions

ICU Patient Rolling 3-Reading Systolic Moving Average

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 vital reading in `patient_vitals`, calculate a rolling 3-reading systolic blood pressure average using: `ROWS BETWEEN 2 PRECEDING AND CURRENT ROW` partitioned by `patient_id` and ordered by `reading_time` ascending. Return: 1. `reading_id` 2. `patient_id` 3. `reading_time` 4. `systolic_bp` 5. `rolling_avg_systolic`: `ROUND(AVG(systolic_bp) OVER (...), 1)` Order results by `patient_id` ascending, then by `reading_time` ascending.

Why Technical Interviewers Ask This

Intensive Care Unit (ICU) clinical telemetry uses moving averages across consecutive vital signs to filter out momentary measurement artifacts and detect true hemodynamic trends.

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 
        reading_id,
        patient_id,
        reading_time,
        systolic_bp,
        ROUND(
          AVG(systolic_bp) OVER (
            PARTITION BY patient_id
            ORDER BY reading_time ASC
            ROWS BETWEEN 2 PRECEDING AND CURRENT ROW
          ),
          1
        ) AS rolling_avg_systolic
      FROM patient_vitals
      ORDER BY patient_id ASC, reading_time ASC;
Approach Breakdown
This query addresses the problem requirements by filtering and structuring data in Window Functions. It meets the target criteria: Rolling systolic moving average per patient across consecutive readings.

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