← Homepage

Window Functions

October 11, 2026

Author: Daniel Jordan Viray

SQL notes · clinical toy data · per-group calculations without collapsing rows

The idea. Aggregates like AVG collapse rows; window functions don't. Each row keeps its identity while the function peers at a window of related rows — the patient's other visits, the previous reading, a running total. One query, row-level detail and group math.

The shape (learn this once, reuse forever)

SELECT patient_id, reading_date, hba1c,
  FUNC(...) OVER (
    PARTITION BY patient_id   -- restart per patient ("per category")
    ORDER BY reading_date     -- the sequence within each group
    ROWS BETWEEN 2 PRECEDING AND CURRENT ROW  -- the frame: which rows count
  )
FROM a1c_readings;

PARTITION BY is "per category": restart the calculation for each patient (or ward, or drug). ORDER BY defines the sequence. The frame (ROWS BETWEEN …) says which rows count — omit it and you get the default, which is rarely what you want for rolling math.

Toy data

a1c_readings — HbA1c lab readings per patient over time

patient_idreading_datehba1c
12024-01-058.2
12024-04-027.9
12024-07-107.9
12024-10-017.4
22024-02-119.1
22024-05-208.8

med_admin — medication doses administered

patient_idadmin_datedose_mg
12024-01-05500.0
12024-02-05500.0
12024-03-05250.0
22024-02-11850.0

Visit number per patient — ROW_NUMBER()

SELECT patient_id, reading_date,
       ROW_NUMBER() OVER (PARTITION BY patient_id ORDER BY reading_date) AS visit_n
FROM a1c_readings ORDER BY patient_id, reading_date;
patient_idreading_datevisit_n
12024-01-051
12024-04-022
12024-07-103
12024-10-014
22024-02-111
22024-05-202

Rank readings within each patient — RANK() vs DENSE_RANK()

SELECT patient_id, hba1c,
       RANK() OVER (PARTITION BY patient_id ORDER BY hba1c DESC) AS rnk,
       DENSE_RANK() OVER (PARTITION BY patient_id ORDER BY hba1c DESC) AS dense_rnk
FROM a1c_readings ORDER BY patient_id, hba1c DESC;
patient_idhba1crnkdense_rnk
18.211
17.922
17.922
17.443
29.111
28.822

Patient 1 has two readings of 7.9 (a tie). RANK() gives both rank 2 then skips to 4; DENSE_RANK() doesn't skip (2, 2, 3). Pick based on whether the skipped numbers matter downstream.

Change since last visit — LAG() (and LEAD() looks forward)

SELECT patient_id, reading_date, hba1c,
       ROUND(hba1c - LAG(hba1c) OVER (PARTITION BY patient_id ORDER BY reading_date), 2)
         AS change_since_last
FROM a1c_readings ORDER BY patient_id, reading_date;
patient_idreading_datehba1cchange_since_last
12024-01-058.2NULL
12024-04-027.9-0.3
12024-07-107.90.0
12024-10-017.4-0.5
22024-02-119.1NULL
22024-05-208.8-0.3

LAG(hba1c) is "the previous row's value, within this patient's sequence." The first row per patient has no previous row → NULL, honestly. LEAD() is the mirror image (next row).

Rolling 3-reading average, per patient

SELECT patient_id, reading_date, hba1c,
       ROUND(AVG(hba1c) OVER (PARTITION BY patient_id ORDER BY reading_date
                              ROWS BETWEEN 2 PRECEDING AND CURRENT ROW), 2)
         AS rolling_avg_3,
       COUNT(*) OVER (PARTITION BY patient_id ORDER BY reading_date
                      ROWS BETWEEN 2 PRECEDING AND CURRENT ROW) AS n_in_avg
FROM a1c_readings ORDER BY patient_id, reading_date;
patient_idreading_datehba1crolling_avg_3n_in_avg
12024-01-058.28.21
12024-04-027.98.052
12024-07-107.98.03
12024-10-017.47.733
22024-02-119.19.11
22024-05-208.88.952

The frame ROWS BETWEEN 2 PRECEDING AND CURRENT ROW is the whole trick: "this reading and the two before it." The hba1c column shows exactly which values went into each average, and n_in_avg makes the edge effect visible: the first reading averages just 1 value, the second averages 2 — only from the third row on is it a true 3-reading average. The frame simply has fewer rows to work with early on; no error, but worth knowing when you read the first few values.

Running total of dose, per patient

SELECT patient_id, admin_date,
       SUM(dose_mg) OVER (PARTITION BY patient_id ORDER BY admin_date
                          ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS running_total_mg
FROM med_admin ORDER BY patient_id, admin_date;
patient_idadmin_daterunning_total_mg
12024-01-05500.0
12024-02-051000.0
12024-03-051250.0
22024-02-11850.0

ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW: "everything from the patient's first row up to this one." Cumulative dose, cumulative cost, cumulative events — same shape.

Watch out.
Prove it. Every query on this page was run against SQLite and the tables show actual output — not hand-typed guesses.