Data + SQL
Week 2 · ~10 h
Much of the job is answering questions from clinical data. A quality nurse wants to know which patients with diabetes are badly controlled. An emergency department manager wants visits per month to plan staffing. A researcher wants everyone whose blood pressure was high last year. Each request sounds like one query, and each one hides decisions: which code counts as diabetes, what “last year” means, whether the count is of patients or of visits, what unit the number is in. The data is full of standard codes and units, and it is messy, so two honest queries can disagree, and you have to explain why.
Getting this wrong has consequences you can't see from the query. Count encounters instead of patients and a clinic looks busier than it is. Compare a glucose in mg/dL against a threshold in mmol/L and every patient becomes diabetic. Search on display text and patients with prediabetes land on a diabetes outreach list. Write a join that drops patients with no test result, and the patient who most needs a phone call never gets one.
This lecture generates one synthetic population, exports it twice (as CSV and as FHIR), loads the CSV into PostgreSQL and answers five clinical questions twice: once in SQL, once with jq over the FHIR files. Then we explain every number that differs. Along the way we look at the code systems that make clinical data comparable, a clinical note that holds facts the codes don't, a FHIR search against a local server, and the Canadian version of the data.
Words you need this week. HbA1c: a blood test that reflects average blood glucose over the previous few months; the usual check on how well diabetes is controlled. ED: emergency department. Care gap: a patient who should have had a test or treatment and has no record of it. Value set: a named list of codes that together mean one thing, such as “any diabetes”. Census: a count of the patients in a hospital or unit at one point in time.
Done when
This week you answer five clinical questions twice, in SQL and in jq. You are done when:
- SQL and jq agree, or each difference is written up.
- Canada track: no record carries a US identifier (exercise 10).
One population, two exports
We start with data we are allowed to break. Synthea simulates patients from birth to today, with visits, labs, diagnoses and prescriptions, and writes them out in several formats. We ask for 20 living patients aged 45 to 75 in Massachusetts, with fixed seeds so the run is repeatable, and switch on the CSV exporter next to the default FHIR one:
$ java -jar synthea-with-dependencies.jar -p 20 -s 21 -cs 21 \
-a 45-75 --exporter.csv.export=true Massachusetts \
| grep -E '^(Records|RNG)'
SLF4J: No SLF4J providers were found.
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#noProviders for further details.
Records: total=22, alive=20, dead=2
RNG=20
$ ls output output/csv
output:
csv
fhir
metadata
output/csv:
allergies.csv
careplans.csv
claims.csv
claims_transactions.csv
conditions.csv
devices.csv
encounters.csv
imaging_studies.csv
immunizations.csv
medications.csv
observations.csv
organizations.csv
patients.csv
payers.csv
payer_transitions.csv
procedures.csv
providers.csv
supplies.csv
$ ls output/fhir | wc -l
24
$ jq --version
jq-1.7
$ du -sh output/csv output/fhir
22M output/csv
106M output/fhir
The first surprise is already there: we asked for 20 patients and got 22
records. -p counts living patients, and Synthea keeps the two who
died during the simulation. A question about “our 20 patients” and a query
over patients.csv already disagree by two, for an honest reason.
Keep that in mind; the dead patients come back later.
The CSV export is one file per kind of thing: patients, encounters, observations (labs, vitals, survey answers), conditions, medications and so on, all linked by UUIDs. The FHIR export is one Bundle per patient, plus two bundles for the hospitals and clinicians they saw. Same simulation, same patients, two shapes. The CSV data dictionary lists every column.
The same result, twice
Look at one HbA1c result (LOINC 4548-4) in each format: the
latest one for patient 86755eb9, plus a smoking-status row for
contrast. We cut the patient and encounter UUIDs out of the CSV so the lines
fit. On the FHIR side we first pull every Observation out of the bundles into
obs.ndjson, one resource per line, which makes later questions
quick to grep and count:
$ head -1 output/csv/observations.csv | cut -d, -f1,4,5,7-9
DATE,CATEGORY,CODE,VALUE,UNITS,TYPE
$ grep 86755eb9 output/csv/observations.csv | grep ,4548-4, \
| tail -1 | cut -d, -f1,4,5,7-9
2026-09-26T05:47:23Z,laboratory,4548-4,8.2,%,numeric
$ grep -m1 ,72166-2, output/csv/observations.csv | cut -d, -f1,4,5,7-9
2017-11-06T01:02:58Z,social-history,72166-2,Ex-smoker (finding),,text
$ jq -c '.entry[].resource | select(.resourceType == "Observation")' \
output/fhir/*.json > obs.ndjson
$ grep 86755eb9 obs.ndjson \
| jq -c 'select(.code.coding[0].code == "4548-4")' | tail -1 \
| jq -c '{effectiveDateTime, valueQuantity, code: .code.coding}'
{"effectiveDateTime":"2026-09-26T01:47:23-04:00","valueQuantity":{"value":8.21,"unit":"%","system":"http://unitsofmeasure.org","code":"%"},"code":[{"system":"http://loinc.org","code":"4548-4","display":"Hemoglobin A1c/Hemoglobin.total in Blood"}]}
The two formats already tell you different things. The CSV has a
CODE column but no column saying which code system it belongs to;
you have to know that observation codes are LOINC. It has one
VALUE column for both numbers and words, with a TYPE
column telling them apart, and it stores times in UTC (the Z). The
FHIR resource names its code system as a URI, puts the number in a
valueQuantity with a UCUM unit, writes the same moment with a
local offset (-04:00), and keeps two decimals: 8.21
where the CSV says 8.2. Every one of those differences shows up
in a count later.
Loading PostgreSQL
We run PostgreSQL in a container and mount the CSV directory read-only. We
don't publish port 5432: on the lab machine it belongs to another PostgreSQL,
and we don't need it, because docker exec runs psql
inside the container. The wait loop asks over TCP on purpose: during first-time
setup the image runs a temporary server on the Unix socket only, and a script
that connects too early gets cut off when it restarts.
$ docker run -d --name pg -e POSTGRES_PASSWORD=lab \
-v "$PWD/output/csv:/csv:ro" postgres:16-alpine
0dda07cdf4c7e2b29713534fb6ffe835b6a04c15cd3f03136654531e54cca5d6
$ docker exec pg sh -c 'until pg_isready -h 127.0.0.1 -q; do sleep 1; done'
$ docker exec pg postgres --version
postgres (PostgreSQL) 16.11
$ docker exec -i pg psql -U postgres -q -v ON_ERROR_STOP=1 < load.sql
NOTICE: table "patients" does not exist, skipping
NOTICE: table "encounters" does not exist, skipping
NOTICE: table "observations" does not exist, skipping
NOTICE: table "conditions" does not exist, skipping
NOTICE: table "medications" does not exist, skipping
NOTICE: table "immunizations" does not exist, skipping
$ docker exec pg psql -U postgres -c '\dt'
List of relations
Schema | Name | Type | Owner
--------+---------------+-------+----------
public | conditions | table | postgres
public | encounters | table | postgres
public | immunizations | table | postgres
public | medications | table | postgres
public | observations | table | postgres
public | patients | table | postgres
(6 rows)
$ docker exec pg psql -U postgres -c \
'SELECT count(*), count(deathdate) AS dead FROM patients'
count | dead
-------+------
22 | 2
(1 row)
The schema in load.sql creates
six tables with the CSV column names and loads them with
\copy. The interesting part is the observations table:
-- VALUE is text: one column holds numbers and coded answers.
CREATE TABLE observations (
date timestamptz, patient uuid, encounter uuid,
category text, code text, description text,
value text, units text, type text);
-- Cast once, at load time, and only the rows that are numbers.
ALTER TABLE observations ADD COLUMN num numeric;
UPDATE observations SET num = value::numeric
WHERE type = 'numeric';
Most columns get real types (uuid, timestamptz,
date), so a malformed date fails the load instead of hiding in a
text column. VALUE can't be numeric, because it also holds answers
like “Never smoked tobacco”. So we keep it as text and add a num
column, filled once at load time for the rows whose TYPE says
numeric. Every query below uses num. The NOTICE
lines are DROP TABLE IF EXISTS saying there was nothing to drop;
they make the script safe to re-run.
Messy on purpose
Why bother with num? Because the obvious queries are wrong in
quiet ways. psql -a echoes each statement before its result:
$ docker exec -i pg psql -U postgres -a < messy.sql
-- One VALUE column holds numbers and words.
SELECT type, count(*) FROM observations GROUP BY type;
type | count
---------+-------
text | 6914
numeric | 10951
(2 rows)
SELECT value, count(*) FROM observations
WHERE code = '72166-2' GROUP BY value;
value | count
--------------------------------+-------
Ex-smoker (finding) | 107
Never smoked tobacco (finding) | 159
(2 rows)
-- Compared as text, '99.1' > '126' is true.
SELECT count(*) AS as_text FROM observations
WHERE code = '2339-0' AND value > '126';
as_text
---------
321
(1 row)
SELECT count(*) AS as_number FROM observations
WHERE code = '2339-0' AND num > 126;
as_number
-----------
12
(1 row)
-- Casting every row fails on the first word.
SELECT count(*) FROM observations
WHERE value::numeric > 126;
-- Encounters dated after the patient died
SELECT left(p.id::text, 8) AS patient, p.deathdate,
e.start::date, e.encounterclass, e.description
FROM patients p JOIN encounters e ON e.patient = p.id
WHERE e.start::date > p.deathdate;
ERROR: invalid input syntax for type numeric: "Ex-smoker (finding)"
patient | deathdate | start | encounterclass | description
----------+------------+------------+----------------+---------------------
ee6bc21b | 2018-12-03 | 2018-12-07 | wellness | Death Certification
0b5eb622 | 2026-08-16 | 2026-08-21 | wellness | Death Certification
(2 rows)
Three lessons in one file. Compared as text, '99.1' > '126'
is true, because strings compare character by character, so the text query
finds 321 “high” glucose results where the numeric one finds 12. Nothing
warned us. Casting the whole column, on the other hand, fails loudly on the
first word it meets, which is the better kind of failure. And two patients
have a wellness encounter dated after their death: Synthea records a death
certification as a visit. A query for “patients seen in the last year” would
count one of them. Real EHR data has its own versions of this: placeholder
dates, test patients, results filed against the wrong visit. Find them before
you trust a count.
Code systems
Clinical data is comparable across systems only because the important
fields are coded. Each code system covers one kind of thing, and a code means
nothing without its system: 4548-4 is HbA1c in LOINC and
nothing in particular anywhere else. The ones you will meet first:
| System | Codes | Example from our data | System URI in FHIR |
|---|---|---|---|
| LOINC | lab tests, vital signs, survey questions, note types | 4548-4 HbA1c | http://loinc.org |
| SNOMED CT | diagnoses, findings, procedures | 44054006 type 2 diabetes | http://snomed.info/sct |
| RxNorm | drugs (US) | 860975 metformin 500 mg ER | http://www.nlm.nih.gov/research/umls/rxnorm |
| ICD-10 | diagnoses on claims and in statistics (ICD-10-CM in the US) | none: Synthea codes conditions in SNOMED CT | |
| CVX | vaccines (US) | Immunization resources | http://hl7.org/fhir/sid/cvx |
| UCUM | units of measure | %, mg/dL, mm[Hg] | http://unitsofmeasure.org |
The CSV export keeps a system name only where a table could hold more than one; for conditions it is always SNOMED CT. The FHIR export names a system on every coding. Here are the systems in one patient's bundle, most frequent first:
$ docker exec pg psql -U postgres -c \
'SELECT system, count(*) FROM conditions GROUP BY 1'
system | count
-----------+-------
SNOMED-CT | 943
(1 row)
$ jq -r '.. | objects | select(.system and .code) | .system' \
output/fhir/*86755eb9*.json | sort | uniq -c | sort -rn | head -12
2538 https://bluebutton.cms.gov/resources/codesystem/adjudication
1415 http://loinc.org
1316 http://snomed.info/sct
537 http://terminology.hl7.org/CodeSystem/ex-serviceplace
537 https://bluebutton.cms.gov/resources/variables/line_cms_type_srvc_cd
413 http://unitsofmeasure.org
400 http://terminology.hl7.org/CodeSystem/observation-category
214 http://terminology.hl7.org/CodeSystem/claim-type
195 http://terminology.hl7.org/CodeSystem/claiminformationcategory
186 http://www.nlm.nih.gov/research/umls/rxnorm
107 http://terminology.hl7.org/CodeSystem/processpriority
107 http://terminology.hl7.org/CodeSystem/claimcareteamrole
LOINC, SNOMED CT, UCUM and RxNorm are there, and so are code systems you didn't ask for: the claims and explanation-of-benefit resources carry CMS Blue Button codes, because Synthea models US insurance. The rule that follows from all this is the one to remember: match on system + code, never on display text. Display text is for people. It changes between releases, differs between vendors and is matched by substrings you didn't intend, as question 4 shows.
Licences matter when you ship code that contains code lists. CPT, the US procedure codes used in billing, is licensed by the AMA. SNOMED CT is free to use in member countries but still licensed: in the US through the NLM, in Canada through Canada Health Infoway. LOINC is free under its own licence. RxNorm comes from the NLM.
Canada: diagnoses in hospital data are coded in ICD-10-CA and procedures in CCI, both maintained by CIHI, not the US ICD-10-CM. Drugs are identified by the Health Canada DIN, and the Canadian Clinical Drug Data Set (CCDD) plays the role RxNorm plays in the US. LOINC, SNOMED CT and UCUM are shared.
Five questions, two ways
Now the real work. We write five clinical questions, answer each in SQL,
then answer it again with jq over the FHIR export. jq is the right second
tool: it reads the same JSON a FHIR server returns, so the habits carry over
to API work in week 4. Three jq moves cover most of it: filter by
resourceType, follow subject.reference back to the
patient, and read code.coding to match system + code.
jq -n with inputs streams every file on the command
line through one program, so output/fhir/*.json is the whole
population.
Before writing either query, pin the question down. Who is counted
(patients, visits, results)? Over what window, in which time zone? Which codes,
in which unit? We pin “the last year” to a literal date,
2025-10-31, so neither tool has its own idea of “now”.
Each question is a pair of files you can download and run: q1-hba1c.sql and q1-hba1c.jq, q2-ed.sql and q2-ed.jq, q3-bp.sql and q3-bp.jq, q4-metformin.sql and q4-metformin.jq, q5-glucose.sql and q5-glucose.jq. The rest of the page uses messy.sql, count.sql, count-obs.jq and to-tx.jq.
Q1: HbA1c above 9% in the last year
HbA1c reflects average blood glucose over the previous few months, and a
high value is the classic sign of poorly controlled diabetes. The question
names a code (LOINC 4548-4), a threshold, a unit (%) and a window,
and asks for patients:
$ docker exec -i pg psql -U postgres -a < q1-hba1c.sql
-- Q1: HbA1c (LOINC 4548-4) above 9% in the last year
SELECT count(*) AS results, count(DISTINCT patient) AS patients
FROM observations
WHERE code = '4548-4' AND num > 9 AND date >= '2025-10-31';
results | patients
---------+----------
0 | 0
(1 row)
-- The same question with no time window
SELECT date::date, left(patient::text, 8) AS patient, value
FROM observations
WHERE code = '4548-4' AND num > 9;
date | patient | value
------------+----------+-------
2018-08-11 | 86755eb9 | 9.7
(1 row)
-- Every type 2 diabetic (SNOMED CT 44054006): latest HbA1c
WITH dm AS (
SELECT DISTINCT patient FROM conditions
WHERE code = '44054006'),
ranked AS (
SELECT patient, date, value, row_number() OVER (
PARTITION BY patient ORDER BY date DESC) AS n
FROM observations WHERE code = '4548-4')
SELECT left(dm.patient::text, 8) AS patient,
r.date::date AS latest, r.value
FROM dm LEFT JOIN ranked r
ON r.patient = dm.patient AND r.n = 1
ORDER BY latest;
patient | latest | value
----------+------------+-------
058228a1 | 2025-12-09 | 6.1
ee37362c | 2025-12-14 | 6.0
c4f2f15f | 2026-08-16 | 6.1
bb61488c | 2026-08-19 | 6.1
86755eb9 | 2026-09-26 | 8.2
(5 rows)
$ cat q1-hba1c.jq
# Q1 over the FHIR export: HbA1c above 9%
[inputs | .entry[].resource
| select(.resourceType == "Observation")
| select(any(.code.coding[];
.system == "http://loinc.org" and .code == "4548-4"))
| select(.valueQuantity.value > 9)]
| {ever: length,
patients: (map(.subject.reference) | unique | length),
last_year: (map(select(.effectiveDateTime >= "2025-10-31"))
| length),
values: map([.effectiveDateTime, .valueQuantity.value])}
$ jq -n -c -f q1-hba1c.jq output/fhir/*.json
{"ever":1,"patients":1,"last_year":0,"values":[["2018-08-11T01:47:23-04:00",9.71]]}
Both tools say zero in the last year, and one result ever: a 9.7% in August
2018. A zero is the answer that most needs checking, because a typo in the code
also returns zero. The second SQL statement drops the window to prove the
filter can match at all, and the third turns the question around: start from
the people who should have been tested, the five patients with type 2
diabetes, and show each one's latest result. A LEFT JOIN keeps
anyone with no HbA1c at all (a care gap); here all five have a result within
the last year. row_number() OVER (PARTITION BY patient ORDER BY date
DESC) is the standard way to pick the latest row per patient, and you
will write it often.
Look again at the jq output: 9.71, where SQL said
9.7. The CSV rounds values to one decimal; FHIR keeps two. At a
threshold of 9 it doesn't matter. Move the threshold onto the rounding and it
does:
$ docker exec pg psql -U postgres -Atc \
"SELECT count(*) FROM observations WHERE code = '4548-4' AND num > 8.2"
1
$ jq -c 'select(.code.coding[0].code == "4548-4")' obs.ndjson \
| jq -s 'map(select(.valueQuantity.value > 8.2)) | length'
13
One result above 8.2 in SQL, thirteen in jq. Twelve results of
8.21 were written to the CSV as 8.2, which is not
above 8.2. The FHIR server we load later agrees with jq. Neither tool is wrong;
they were given different numbers. When you compare exports, compare at the
precision of the coarser one, and say so.
AI this week: let it draft queries; check each against a sample you counted by hand.
Q2: ED visits per month
An emergency department visit is an encounter, so this question counts
visits, not patients; we show both. The opposite mistake, counting encounters
when the question asked about patients, is one of the commonest in this work,
so put both numbers side by side until you are sure which one was asked for.
The CSV calls the encounter class
emergency. FHIR uses the HL7
ActCode
EMER. Same idea, different code, and a mapping you must get
right:
$ docker exec -i pg psql -U postgres -a < q2-ed.sql
-- Q2: ED visits per month since January 2024
SELECT to_char(start, 'YYYY-MM') AS month,
count(*) AS visits, count(DISTINCT patient) AS patients
FROM encounters
WHERE encounterclass = 'emergency' AND start >= '2024-01-01'
GROUP BY 1 ORDER BY 1;
month | visits | patients
---------+--------+----------
2024-02 | 1 | 1
2024-08 | 1 | 1
2024-10 | 2 | 2
2024-12 | 2 | 2
2025-02 | 1 | 1
2025-08 | 2 | 2
2026-06 | 1 | 1
2026-10 | 1 | 1
(8 rows)
-- October 2024 by day: UTC, then Boston time
SELECT start::date AS utc_day,
(start AT TIME ZONE 'America/New_York')::date AS local_day
FROM encounters
WHERE encounterclass = 'emergency'
AND start BETWEEN '2024-10-01' AND '2024-11-01';
utc_day | local_day
------------+------------
2024-10-05 | 2024-10-05
2024-10-05 | 2024-10-04
(2 rows)
$ cat q2-ed.jq
# Q2 over the FHIR export: ED visits per month
[inputs | .entry[].resource
| select(.resourceType == "Encounter" and .class.code == "EMER")
| select(.period.start >= "2024-01-01")
| {month: .period.start[:7], day: .period.start[:10],
patient: .subject.reference}]
| group_by(.month)[]
| [.[0].month, length, (map(.patient) | unique | length),
(map(.day) | join(" "))]
| @tsv
$ jq -n -r -f q2-ed.jq output/fhir/*.json
2024-02 1 1 2024-02-09
2024-08 1 1 2024-08-14
2024-10 2 2 2024-10-04 2024-10-05
2024-12 2 2 2024-12-29 2024-12-25
2025-02 1 1 2025-02-11
2025-08 2 2 2025-08-19 2025-08-08
2026-06 1 1 2026-06-12
2026-10 1 1 2026-10-25
The months agree. The days don't. In October 2024 SQL puts both visits on
the 5th, and jq puts one on the 4th. The CSV stores UTC; the FHIR export writes
Boston time with its offset, and our jq takes the first ten characters of that
local string. A visit late in the evening of 4 October in Boston is already
5 October in UTC. The second SQL statement converts to
America/New_York and
gets jq's answer. Hospitals report by local day, so local time is usually
right for a census; whichever you choose, choose it on purpose. A monthly
report can show the same problem when a visit falls near midnight at the end
of a month.
Tested: in this Synthea build, the CSV timestamps we looked at end in
Z(UTC), and the FHIR export writes the same moments with a-04:00or-05:00offset, depending on daylight saving time. Comparing those strings compares local dates, not instants.
Q3: systolic blood pressure of 140 or more
Systolic pressure has its own LOINC code, 8480-6. SQL finds
it at once. The obvious jq query finds nothing:
$ docker exec -i pg psql -U postgres -a < q3-bp.sql
-- Q3: systolic BP (LOINC 8480-6) of 140 mm[Hg] or more
SELECT date::date, left(patient::text, 8) AS patient,
num, units
FROM observations
WHERE code = '8480-6' AND num >= 140 AND date >= '2025-10-31'
ORDER BY 1;
date | patient | num | units
------------+----------+-------+--------
2025-12-14 | ee37362c | 142.0 | mm[Hg]
2026-08-16 | c4f2f15f | 145.0 | mm[Hg]
(2 rows)
$ jq -c 'select(.code.coding[0].code == "8480-6")' obs.ndjson | wc -l
0
$ cat q3-bp.jq
# Q3 over the FHIR export. Systolic BP usually lives inside a
# blood pressure panel (LOINC 85354-9) as a component.
inputs | .entry[].resource
| select(.resourceType == "Observation"
and .effectiveDateTime >= "2025-10-31") as $obs
| (.component // [.])[]
| select(any(.code.coding[];
.system == "http://loinc.org" and .code == "8480-6"))
| select(.valueQuantity.value >= 140)
| [$obs.effectiveDateTime[:10], $obs.subject.reference[9:17],
$obs.code.coding[0].code, .valueQuantity.value,
.valueQuantity.unit]
| @tsv
$ jq -n -r -f q3-bp.jq output/fhir/*.json
2025-12-14 ee37362c 85354-9 142 mm[Hg]
2026-08-15 c4f2f15f 85354-9 145 mm[Hg]
Zero isn't a data problem; it's a modelling difference. In FHIR, a blood
pressure is one Observation coded as a panel (85354-9) with the
systolic and diastolic values as components, as the
Observation page
describes. The CSV flattens each component into its own row. The fixed jq
looks inside components (and falls back to the resource itself when there are
none), and finds the same two readings. Note the second date once more:
2026-08-16 in SQL, 2026-08-15 in jq. Same reading,
same time-zone story as Q2.
Q4: type 2 diabetes and metformin
How many patients with type 2 diabetes are on metformin today? The first SQL statement shows why the codes matter, by doing it wrong:
$ docker exec -i pg psql -U postgres -a < q4-metformin.sql
-- Q4: patients with type 2 diabetes on metformin today.
-- Matching on display text catches prediabetes too:
SELECT code, description, count(DISTINCT patient)
FROM conditions WHERE description ILIKE '%diabetes%'
GROUP BY 1, 2 ORDER BY 3 DESC;
code | description | count
-----------------+------------------------------------------------------------------------+-------
714628002 | Prediabetes (finding) | 15
44054006 | Diabetes mellitus type 2 (disorder) | 5
368581000119106 | Neuropathy due to type 2 diabetes mellitus (disorder) | 2
127013003 | Disorder of kidney due to diabetes mellitus (disorder) | 2
157141000119108 | Proteinuria due to type 2 diabetes mellitus (disorder) | 1
1551000119108 | Nonproliferative diabetic retinopathy due to type II diabetes mellitus | 1
90781000119102 | Microalbuminuria due to type 2 diabetes mellitus (disorder) | 1
(7 rows)
SELECT count(DISTINCT patient) AS by_text FROM conditions
WHERE description ILIKE '%diabetes%';
by_text
---------
17
(1 row)
-- Matching on the code (SNOMED CT 44054006), then joining
-- metformin (RxNorm 860975) with no STOP date
SELECT count(DISTINCT c.patient) AS diabetics,
count(DISTINCT m.patient) AS on_metformin,
count(m.patient) AS rows_joined
FROM conditions c
LEFT JOIN medications m
ON m.patient = c.patient AND m.code = '860975'
AND m.stop IS NULL
WHERE c.code = '44054006' AND c.stop IS NULL;
diabetics | on_metformin | rows_joined
-----------+--------------+-------------
5 | 5 | 5
(1 row)
-- Rows are prescriptions, not patients
SELECT count(*) AS prescriptions, count(DISTINCT patient)
FROM medications WHERE code = '860975';
prescriptions | count
---------------+-------
54 | 5
(1 row)
$ cat q4-metformin.jq
# Q4 over the FHIR export
def coded($sys; $code):
any(.coding[]?; .system == $sys and .code == $code);
[inputs | .entry[].resource] as $all
| ($all | map(select(.resourceType == "Condition"
and (.code | coded("http://snomed.info/sct"; "44054006"))
and .clinicalStatus.coding[0].code == "active")
| .subject.reference) | unique) as $dm
| ($all | map(select(.resourceType == "MedicationRequest"
and (.medicationCodeableConcept | coded(
"http://www.nlm.nih.gov/research/umls/rxnorm"; "860975"))
and .status == "active")
| .subject.reference) | unique) as $met
| {diabetics: ($dm | length),
on_metformin: ($met | map(select(IN($dm[]))) | length)}
$ jq -n -c -f q4-metformin.jq output/fhir/*.json
{"diabetics":5,"on_metformin":5}
Searching display text for “diabetes” finds 17 patients, because 15
patients have prediabetes, and complications like diabetic kidney
disease are separate codes. Matching SNOMED CT 44054006 finds 5.
If you do want “any diabetes”, build the list of codes on purpose (a value
set), don't let a substring build it for you. The join then needs both a
code and a state: RxNorm 860975 (24-hour metformin 500 mg) with
no stop date. The last statement is the classic trap: 54 metformin rows but
only 5 patients, because each refill is a new prescription row. Count
DISTINCT patient when the question is about people.
In jq, “today” has to come from different fields: a Condition's
clinicalStatus and a MedicationRequest's status.
coded is a small helper that matches system + code on any coding,
and IN intersects the two patient lists. Both tools say 5 and 5.
They agree here because Synthea derives the CSV stop date and the FHIR status
from the same event. In a real EHR the two are separate fields with separate
errors, and an active order for a patient who died is a common finding.
Q5: glucose and units
This question is about a classic mistake: comparing values without converting units. Canadian labs report glucose in mmol/L; Synthea's US-style data is in mg/dL. Suppose a Canadian colleague asks for glucose results of 7.0 mmol/L or more in the last year. Glucose also has two common LOINC codes, for whole blood and for serum or plasma, so we ask for both:
$ docker exec -i pg psql -U postgres -a < q5-glucose.sql
-- Q5: glucose of 7.0 mmol/L or more in the last year.
-- Two LOINC codes; values are mg/dL; 1 mmol/L = 18.016 mg/dL
SELECT code, units, count(*) AS results,
count(*) FILTER (WHERE num >= 7.0) AS unconverted,
count(*) FILTER (WHERE num / 18.016 >= 7.0) AS converted
FROM observations
WHERE code IN ('2339-0', '2345-7') AND date >= '2025-10-31'
GROUP BY 1, 2;
code | units | results | unconverted | converted
--------+-------+---------+-------------+-----------
2339-0 | mg/dL | 20 | 20 | 1
2345-7 | mg/dL | 1 | 1 | 0
(2 rows)
SELECT date::date, left(patient::text, 8) AS patient, num,
round(num / 18.016, 1) AS mmol_l
FROM observations
WHERE code IN ('2339-0', '2345-7') AND date >= '2025-10-31'
AND num / 18.016 >= 7.0;
date | patient | num | mmol_l
------------+----------+-------+--------
2026-09-26 | 86755eb9 | 140.2 | 7.8
(1 row)
$ cat q5-glucose.jq
# Q5 over the FHIR export: convert to mmol/L before comparing
inputs | .entry[].resource
| select(.resourceType == "Observation"
and .effectiveDateTime >= "2025-10-31")
| select(any(.code.coding[]; .system == "http://loinc.org"
and (.code == "2339-0" or .code == "2345-7")))
| .valueQuantity as $q
| (if $q.code == "mg/dL" then $q.value / 18.016
elif $q.code == "mmol/L" then $q.value
else error("unexpected unit \($q.code)") end) as $mmol
| select($mmol >= 7.0)
| [.effectiveDateTime[:10], .subject.reference[9:17],
$q.value, ($mmol * 10 | round / 10)]
| @tsv
$ jq -n -r -f q5-glucose.jq output/fhir/*.json
2026-09-26 86755eb9 140.2 7.8
Applied straight to mg/dL values, the 7.0 threshold flags all 21 results. Converted (one mmol/L of glucose is 18.016 mg/dL, from its molar mass of 180.16 g/mol), it flags one. The jq version checks the UCUM unit code on every value and stops with an error on a unit it doesn't know, rather than guessing. That is the behaviour you want: in real feeds, one lab's mmol/L and another's mg/dL arrive under the same LOINC code.
Canada: SI units are the norm in Canadian lab reports, so mmol/L for glucose. If you build a report from US data or from a US vendor's defaults, convert first and print the unit next to every number. Your unit tests should include a value in each unit.
Explaining every difference
Before trusting any per-question count, reconcile the totals. SQL has 17,865 observation rows; the FHIR export has fewer Observation resources:
$ docker exec -i pg psql -U postgres -a < count.sql
-- Observation rows, and the ones with no category
SELECT count(*),
count(*) FILTER (WHERE category IS NULL) AS no_category
FROM observations;
count | no_category
-------+-------------
17865 | 693
(1 row)
SELECT code, description, count(*) FROM observations
WHERE category IS NULL GROUP BY 1, 2;
code | description | count
------+-------------+-------
DALY | DALY | 231
QALY | QALY | 231
QOLS | QOLS | 231
(3 rows)
$ wc -l < obs.ndjson
11572
$ cat count-obs.jq
# Run with jq -s over one Observation per line.
# Why FHIR has fewer Observations than observations.csv
{resources: length,
with_components: map(select(.component)) | length,
rows_if_flattened:
map(if .component then (.component | length) else 1 end)
| add,
panels: map(select(.component) | .code.coding[0].code)
| group_by(.) | map({(.[0]): length}) | add}
$ jq -s -c -f count-obs.jq obs.ndjson
{"resources":11572,"with_components":546,"rows_if_flattened":17172,"panels":{"85354-9":274,"93025-5":266,"X9999-0":6}}
Every row is accounted for. 546 FHIR Observations have components: 274
blood pressure panels (85354-9), 266 PRAPARE social-needs
questionnaires (93025-5) and 6 of Synthea's own operative-status
panels (X9999-0, a placeholder code). Flattened, they and the
plain Observations make 17,172 rows. The other
693 CSV rows (DALY, QALY and QOLS: Synthea's quality-of-life measures) have no
category and no FHIR Observation at all. 17,172 + 693 = 17,865. That is the
level of detail to aim for when you explain a difference. Here is the full
list from this lecture:
| What | SQL / CSV | jq / FHIR | Why |
|---|---|---|---|
| Patients | 22 rows for -p 20 | 22 bundles | -p counts living patients; 2 died and are kept |
| Observations | 17,865 rows | 11,572 resources | components flattened to rows; DALY/QALY/QOLS only in CSV |
| Glucose above 126 mg/dL | 321 as text, 12 as numbers | text comparison is character by character | |
| Q1 HbA1c, highest value | 9.7 | 9.71 | CSV rounds to one decimal |
| Q1 probe: HbA1c above 8.2 | 1 | 13 (HAPI: 13) | twelve 8.21s became 8.2 |
| Q2 ED visits, October 2024 by day | 5th, 5th | 4th, 5th | UTC versus Boston time |
| Q3 systolic 140 or more | 2 | 0 naive, 2 with components | FHIR keeps systolic inside the BP panel |
| Q3 date of one reading | 2026-08-16 | 2026-08-15 | UTC versus Boston time |
| Q4 diabetes | 17 by display text, 5 by code | 5 by code | display text matches prediabetes and complications |
| Q4 metformin | 54 rows, 5 patients | 5 patients | rows are prescriptions, not people |
| Q5 glucose 7.0 mmol/L or more | 21 unconverted, 1 converted | 1 | values are mg/dL; 1 mmol/L = 18.016 mg/dL |
Most of these fall into a handful of families: what is counted (patients, encounters, rows), when (window, time zone), how values are stored (type, precision, unit), and how the two formats model the same fact (flattened rows versus components, CSV-only measures). Missing data is the last family: a query that starts from results can't see the patient who has none, which is why Q1 started from the diabetics.
Notes and documents
Coded data is what a system can query; notes are where clinicians write
what happened. Synthea's notes are DocumentReference resources, one per
encounter, with the text base64-encoded in content.attachment.data.
Here is the latest one for the patient with the 9.7% HbA1c:
$ jq -c '.entry[].resource | select(.resourceType == "DocumentReference")' \
output/fhir/*86755eb9*.json > notes.ndjson
$ wc -l < notes.ndjson
50
$ jq -s -c 'max_by(.date) | {date, type: [.type.coding[].code]}' notes.ndjson
{"date":"2026-10-10T01:47:23.124-04:00","type":["34117-2","51847-2"]}
$ jq -s -r 'max_by(.date) | .content[0].attachment.data' notes.ndjson \
| base64 -d
2026-10-10
# Chief Complaint
- Blurred Vision
# History of Present Illness
Elvira561 Ester635 is a 52 year-old hispanic black female. Patient has a history of acute bacterial sinusitis (disorder), severe anxiety (panic) (finding), medication review due (situation), unemployed (finding), leaking dental filling (finding), viral sinusitis (disorder), part-time employment (finding), acute bronchitis (disorder), limited social contact (finding), reports of violence in the environment (finding), full-time employment (finding), dental filling lost (finding), gingivitis (disorder), myocardial infarction (disorder), loose dental filling (finding), stress (finding).
# Social History
Patient is married. Patient has never smoked.
Patient identifies as heterosexual.
Patient comes from a middle socioeconomic background.
Patient has completed some college courses.
Patient currently has Medicare.
# Allergies
No Known Allergies.
# Medications
acetaminophen 325 mg oral tablet; 24 hr metformin hydrochloride 500 mg extended release oral tablet; 50 ml bivalirudin 5 mg/ml injection; hydrochlorothiazide 25 mg oral tablet; nitroglycerin 0.4 mg sublingual tablet; etonogestrel 68 mg drug implant; 3 ml liraglutide 6 mg/ml pen injector; 1 ml medroxyprogesterone acetate 150 mg/ml injection; aspirin 325 mg oral tablet; {28 (norethindrone 0.35 mg oral tablet) } pack [camila 28 day]; clopidogrel 300 mg oral tablet; sodium fluoride 0.0272 mg/mg oral gel
# Assessment and Plan
Patient is presenting with loose dental filling (finding).
## Plan
The following procedures were conducted:
- dental consultation and report (procedure)
- dental care (regime/therapy)
- removal of supragingival plaque and calculus from all teeth using dental instrument (procedure)
- removal of subgingival plaque and calculus from all teeth using dental instrument (procedure)
- dental plain x-ray bitewing (procedure)
- examination of gingivae (procedure)
- restoration of tooth with coverage of all cusps using dental filling material (procedure)
- dental fluoride treatment (procedure)
- oral health education (procedure)
The patient was prescribed the following medications:
- sodium fluoride 0.0272 mg/mg oral gel
Read it against the coded data and list what only the note says. The chief
complaint, “Blurred Vision”, is not coded anywhere for that visit. The note
also states marital status, education, socioeconomic background and insurance
in one place, and gives a medication list as prose. Some of this is coded
elsewhere (smoking status is LOINC 72166-2), some only as a
questionnaire answer, some not at all. Synthea's notes are generated from the
coded data, so they are tidier than real ones. Real notes add negations (“no
chest pain”), family history and plans that never become orders, and that is
why natural-language processing exists.
Exchange between organizations in the US mostly uses documents, and the main format is C-CDA (Consolidated Clinical Document Architecture): XML with coded sections plus human-readable narrative. In FHIR, a document is referenced by a DocumentReference, as here.
The same questions from a FHIR server
We use a local HAPI server here, not the public HAPI
test server. Public test servers hold whatever strangers upload, and you must
never send them real data. With a local server
the data is our synthetic population. Synthea's bundles refer to
each other with urn:uuid: references that only resolve inside
the bundle, so to-tx.jq builds
one small transaction with the 22 patients and their 228 HbA1c results and
rewrites the references to Patient/<id>:
$ docker run -d --name hapi -p 8080:8080 hapiproject/hapi:latest
1661f551669d0991c331e3ee5956bf0e971db07c98bc20fb0fedc794187e5f12
$ until curl -sf -o /dev/null localhost:8080/fhir/metadata; do sleep 2; done
$ curl -s localhost:8080/fhir/metadata | jq -r .software.version
8.12.0
$ jq -n -f to-tx.jq output/fhir/*.json > tx.json
$ jq '.entry | length' tx.json
250
$ curl -s localhost:8080/fhir -H 'Content-Type: application/fhir+json' \
--data-binary @tx.json | jq -r '.entry[].response.status' | uniq -c
250 201 Created
$ URL='http://localhost:8080/fhir/Patient'
$ curl -s -G "$URL" -H 'Accept: application/fhir+json' \
-d _count=3 -d _elements=name,birthDate \
| jq -r '.entry[]?.resource | [.id, (.name[0].family // "?"), (.birthDate // "?")] | @tsv'
ee37362c-b39e-aeb4-e655-7b3461d5bf6b Donnelly343 1959-07-26
bb61488c-df41-1159-ddc5-4a472c37a869 Kirlin939 1966-10-26
7ac5b274-b2f4-3454-295a-33bfe37fd9e9 Fahey393 1968-02-20
$ OBS='http://localhost:8080/fhir/Observation'
$ curl -s -G "$OBS" -d code='http://loinc.org|4548-4' \
-d value-quantity=gt9 -d _summary=count | jq .total
1
$ curl -s -G "$OBS" -d code='http://loinc.org|4548-4' \
-d value-quantity=gt9 -d date=ge2025-10-31 \
-d _summary=count | jq .total
0
$ curl -s -G "$OBS" -d code='http://loinc.org|4548-4' \
-d value-quantity=gt8.2 -d _summary=count | jq .total
13
$ docker rm -f hapi
hapi
Reading the command: curl -G sends the
-d pairs as a query string, _count limits the page,
_elements trims each resource, and jq turns the Bundle into
tab-separated rows. The ? in .entry[]? keeps an empty
result from becoming an error. Then a third answer to Q1, from
FHIR search parameters: a
token search on code with system and code separated by
|, a quantity search with the gt prefix, a date
search, and _summary=count to return only the total. The server
says 1 ever and 0 in the last year, like the other two tools, and 13 above
8.2, like jq: it has FHIR's two decimals.
Tested: HAPI 8.12.0 accepted all 250 PUTs in one transaction (250 ×
201 Created), and thevalue-quantity=gt8.2search counted the 8.21 results. We didn't re-run the public-server version of the example; the command is unchanged apart from the URL.
SQL Server and reporting databases
You will rarely query an EHR's live database. Vendors copy it nightly into
a reporting database, and that is where analysts work. Epic's Clarity is the
best-known example, and it is queried in SQL. Many of these run on Microsoft
SQL Server, so if you target Microsoft shops, load the same CSVs into SQL
Server and port the five questions to T-SQL. The ideas carry over unchanged:
joins, row_number() OVER (…), distinct counts, explicit time
zones. The syntax differs in places, for example TOP instead of
LIMIT, DATEADD for date arithmetic, and
TRY_CAST to turn a non-numeric value into NULL
instead of an error; the
T-SQL
reference has the details. We didn't run SQL Server for this page, so
nothing here was tested against it.
Canada track
Synthea's international configurations swap the geography, demographics and
facilities. The ca folder from synthea-international is placed on
the classpath ahead of the jar, so its synthea.properties and
data files win:
$ ls ca
geography
payers
providers
synthea.properties
$ java -cp ca:synthea-with-dependencies.jar App -p 3 -s 7 -cs 7 \
--exporter.baseDirectory=./output-ca Ontario | grep Records
SLF4J: No SLF4J providers were found.
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#noProviders for further details.
Records: total=3, alive=3, dead=0
$ jq -c '.entry[].resource | select(.resourceType == "Patient")' \
output-ca/fhir/[A-Z]*.json > ca-patients.ndjson
$ jq -r '[.birthDate, .address[0].city, .address[0].postalCode] | @tsv' \
ca-patients.ndjson
2004-11-16 London N5Z
2003-11-06 Burlington L7R
2012-03-07 Vaughan L0J
$ jq -c '.identifier[]' ca-patients.ndjson \
| jq -r '[.type.coding[0].code // "-", .system, .value] | @tsv'
- https://github.com/synthetichealth/synthea bb0f1798-a377-3418-41f5-a58c8c6ed14d
MR http://hospital.smarthealthit.org bb0f1798-a377-3418-41f5-a58c8c6ed14d
SS http://hl7.org/fhir/sid/us-ssn 999-60-5596
DL urn:oid:2.16.840.1.113883.4.3.25 S99975303
PPN http://hl7.org/fhir/sid/passport-USA X49812378X
- https://github.com/synthetichealth/synthea 592ad309-7d98-4a5d-dbcb-2a5c6379c99e
MR http://hospital.smarthealthit.org 592ad309-7d98-4a5d-dbcb-2a5c6379c99e
SS http://hl7.org/fhir/sid/us-ssn 999-89-7145
DL urn:oid:2.16.840.1.113883.4.3.25 S99953534
PPN http://hl7.org/fhir/sid/passport-USA X01004394X
- https://github.com/synthetichealth/synthea bfc9945a-0277-0b39-6d0f-cea74f9dbeef
MR http://hospital.smarthealthit.org bfc9945a-0277-0b39-6d0f-cea74f9dbeef
SS http://hl7.org/fhir/sid/us-ssn 999-75-9769
$ jq -r '.. | objects | select(.system and .code) | .system' \
output-ca/fhir/[A-Z]*.json | sort -u | grep -v terminology
http://dicom.nema.org/medical/dicom/current/output/chtml/part16/sect_CID_29.html
http://hl7.org/fhir/sid/cvx
http://loinc.org
https://bluebutton.cms.gov/resources/codesystem/adjudication
https://bluebutton.cms.gov/resources/variables/line_cms_type_srvc_cd
http://snomed.info/sct
http://unitsofmeasure.org
http://www.nlm.nih.gov/research/umls/rxnorm
urn:ietf:bcp:47
urn:ietf:rfc:3986
The addresses are Canadian, with only the first three characters of each
postal code. The identifiers are not. The adults carry a US Social Security
number, a Massachusetts driver's licence (the OID ending in
.4.3.25) and a US passport; the patient born in 2012 carries
only the SSN. The
claims still use US Blue Button codes, and drugs and vaccines are RxNorm and
CVX. That is fine for learning SQL and jq, and wrong for anything that will be
shown as Canadian data.
The Canada track asks you to fix that. Replace the US identifiers with a
provincial health card number (use an example.org system for
synthetic numbers, never a real issuer's), and map the RxNorm drugs to Health
Canada DINs or CCDD codes. Check the result with a query, not by eye: no
record should carry a us-ssn, passport-USA or US
driver's-licence identifier. We didn't build the mapping for this page.
Tested: Synthea's Canada config gave Ontario addresses (3-character postal prefixes, one in the wrong city) but kept a US SSN, passport and Massachusetts driver's licence on every patient, plus RxNorm and CVX codes. Our 31 Oct run matches, except that the patient born in 2012 had only the SSN.
Exercises
- Why match codes on system + code instead of display text? Use the Q4 output to give two concrete ways display text fails.
- Name two honest reasons SQL and jq counts can differ. For each, write the one-line fix that makes them agree, and say which answer you would report.
- Which code system holds a lab test? A diagnosis? A drug? A vaccine? A unit? Find one example of each in a Synthea FHIR bundle with jq.
- Rewrite Q2 in SQL so both months and days are Boston-local, and show that it now agrees with jq day by day since 2024.
- Care gaps: list the patients with type 2 diabetes whose latest HbA1c is
more than six months old, or who have none. Do it in SQL with a
LEFT JOINand in jq. Then delete one patient's HbA1c rows and check that both queries still report that patient. - Write a jq program that produces exactly the observation rows the CSV holds for one patient (flatten the components). Which rows can't you produce, and why?
- Add a sixth question of your own that involves a unit or a time window, answer it both ways, and write up any difference in a table like the one above.
- Read one note and list the facts it holds that the coded data doesn't. For each fact, find out whether it exists anywhere as a coded resource.
- If you target Microsoft shops: load the CSVs into SQL Server and port
load.sqland Q1 to T-SQL (TRY_CAST,TOP,DATEADD). Do the counts match PostgreSQL? - Canada track: swap the US identifiers for a health card number and map RxNorm drugs to DIN/CCDD. Write a jq check that exits non-zero if any record still carries a US identifier, and run it in CI.
Read
- FHIR search
- Synthea CSV export
- CACDI
- Synthea CSV data dictionary
- FHIR R4 Observation (components)
- FHIR R4 DocumentReference
- jq manual
- PostgreSQL 16: window functions
- LOINC licence
- SNOMED CT at the NLM
- RxNorm
- UCUM
- HL7 C-CDA
- T-SQL reference
- Health Canada Drug Product Database (DIN)
- Canadian Clinical Drug Data Set (CCDD)
Tested with
Every command on this page was run on 31 Oct 2026 against the course lab:
Synthea (master build of 21 Oct 2026), PostgreSQL 16.11 in Docker
(postgres:16-alpine), jq 1.7 and a local HAPI FHIR 8.12.0
server. The outputs are
copied from one run. Yours will differ in timestamps and container ids;
with the same seeds, the patients and counts should match.
Course content © 2026 HeyItWorked. All rights reserved.
Site design adapted from The Missing Semester of Your CS Education under CC BY-NC-SA 4.0. See copyright and license.