Notes, XrefCodes

Inside XrefCodes: from official code sets to warehouse SQL

How a plain-text code search grew into value sets, patient groups and generated SQL.

17 min read DjangoHealthcare dataSQL

In this article (6 sections)
  1. Why XrefCodes exists
  2. Bringing in the official sources
  3. Finding codes and code lists
  4. From code lists to patients and SQL
  5. Keeping the data current
  6. Principles and where it stands

Healthcare analytics runs on codes. A diagnosis is an ICD-10-CM code, a lab test is a LOINC code, a drug is an RxNorm concept or an NDC, a vaccine is a CVX code. Almost every question an analytics team is asked — how many patients with diabetes had an HbA1c test last year, which encounters should count toward a quality measure, what a free-text note actually describes — starts with finding the right set of codes.

XrefCodes is a tool for that first step, and for the steps that follow it. It loads the official code sets, makes them searchable in plain language, lets you save codes as lists, combine those lists into patient groups and quality measures, and then writes the SQL to find those patients in your own data warehouse. This note explains how it is put together and why it is built the way it is.

Why XrefCodes exists

The problem

Code lookups come up constantly in healthcare analytics: for research cohorts, for audits, for queries behind quality measures, and for mapping free text to specific codes when documentation in the electronic medical record is incomplete or only exists as notes.

In practice, many people search for codes on a general web search engine. That tends to produce a few codes rather than the full set, and often from an outdated release. ICD-10-CM changes every fiscal year; value sets used in quality measures change every reporting year. A list that was right last year can quietly miss new codes or include retired ones.

There is also a knowledge problem. Few people remember codes, and the official files are organised for the people who maintain them, not the people who use them. Someone who knows they need “type 2 diabetes with kidney complications” should be able to type that and see every matching code across every code system, with the release it came from.

So the goal was simple to state: one place to find every code, by plain text, across all the major code systems, always showing which release each result came from. Everything else in XrefCodes grew from that.

What it does, end to end

The product follows the same path an analyst does:

  1. Find codes. One search across ICD-10-CM, ICD-10-PCS, SNOMED CT, LOINC, RxNorm, NDC, CVX and HCPCS.
  2. Save them as a code list (a value set), or start from one of the 12,000+ value sets published by the National Library of Medicine.
  3. Describe a patient group in plain sentences: patients who have codes from one list and don’t have codes from another, within an age range and a time window. Or describe a quality measure, with its population, denominator, exclusions and numerator.
  4. Generate SQL for your own warehouse, as a dbt project or plain SQL, in seven SQL dialects.
CMS · CDC · FDA ICD-10 · HCPCS CVX · NDC NLM SNOMED CT · RxNorm VSAC · eCQMs Regenstrief LOINC answer lists Loaders, run as background jobs back up → load → update in place One Postgres database code systems · codes · value sets Search Code lists Patient groups SQL generator + your data map dbt project or SQL · 7 dialects
Official files go in at the top; SQL for your own warehouse comes out at the bottom.

The rest of this note follows the same order: bringing in the official sources, finding codes and code lists, turning them into patient groups and SQL, and keeping the data current.

Bringing in the official sources

Before anything can be searched, the official files have to be loaded, made to look alike, and kept within each publisher’s terms.

Gathering the sources

There is no single download for “all healthcare codes”. Each code system has its own publisher, its own file format, its own release schedule and its own terms of use.

Source Publisher How it arrives Terms
ICD-10-CM, ICD-10-PCS CMS Yearly text files Public domain
HCPCS Level II CMS Quarterly files Public domain
CVX CDC A single table Public domain
NDC Directory FDA Package and product files Public domain
SNOMED CT (US Edition) NLM RF2 release, twice a year Free licence
RxNorm NLM Release files and the RxNav API Free licence
VSAC value sets NLM An API, one value set at a time Free licence
LOINC Regenstrief Manual download after accepting a licence Free licence
CMS eCQMs, HRSA UDS CMS, HRSA Spreadsheets, measure packages, a PDF manual Public

Each source gets its own loader, and every loader follows the same rules. It reads a local copy of the official file rather than fetching data mid-load, so every load can be repeated and traced back to a specific file. It updates rows in place, so running it twice is harmless. And it never deletes codes: a code that disappears from a new release is marked inactive, because old data in a warehouse still uses it.

Some sources were straightforward. Others took real work:

  • VSAC value sets are only available through an API, and the catalogue has to be walked page by page with no way to jump ahead. A full pass over roughly 18,000 value sets takes more than an hour, so the loader retries with backoff, writes each page as it goes, and can resume cheaply if a run is interrupted.
  • SNOMED CT ships as tab-separated files that don’t use quote characters at all. A standard CSV reader treats a stray quotation mark inside a description as the start of a quoted field and swallows the following lines. The fix was a one-line setting, but finding it took a crash on real data.
  • LOINC can only be downloaded by a person who has accepted the licence on the publisher’s site, so its loader starts from a file someone has fetched by hand.
  • ICD-10-CM is published without the dot (“E119”), while most people and many warehouses write it with one (“E11.9”). XrefCodes stores one canonical dotted form and handles the other spellings later, when SQL is generated.

Today the database holds a little over half a million SNOMED CT concepts with their hierarchy, about 114,000 LOINC codes, around 99,000 RxNorm concepts, 219,000 NDC packages, every ICD-10 code for the current fiscal year, 12,028 VSAC value sets and 73 eCQMs.

One shape for every code system

The sources look nothing alike, but once loaded they share one simple shape. Every code belongs to a code system. Codes are grouped into value sets. Value sets are combined into patient groups. Measures reference value sets in specific roles.

Code system ICD-10-CM, FY2027, loaded on… Code E11.9 · Type 2 diabetes mellitus Value set (code list) from VSAC, or your own Patient group groups → has / doesn't have Measure population · denominator · numerator
Every layer keeps a link back to the code system and release it came from.

Two decisions in this model matter more than they look.

Every code keeps its own code system, even inside a value set. A single VSAC value set for diabetes can mix ICD-10-CM, SNOMED CT and LOINC codes. Each code system has its own terms of use (see below), so those terms have to apply to each code individually rather than to the list as a whole.

Provenance is always visible. Next to every code, XrefCodes shows its code system, its release, and when that release was loaded. If a newer official release exists, the app says so rather than quietly serving old data. XrefCodes is a reference, not an advisor: it shows what the official sources say, and it does not suggest which code to use for a patient or a bill.

Following each publisher’s terms

Each code set comes with its publisher’s terms of use, and they are not all the same. Some are public domain; others are free to use under a licence with conditions such as attribution.

Because every code keeps its own code system, those terms can be applied code by code rather than list by list: on every page, every export, the API and every generated file. Exports cover only what a user has built or searched for, and XrefCodes does not offer bulk downloads of code systems. CPT codes, which are licensed separately by the American Medical Association, are not included in XrefCodes.

Finding codes and code lists

With every source in one shape, the next problem is finding the right codes quickly, and keeping track of how published lists change from year to year.

Search when you don’t know the code

Search is the part most people use, and it has to handle two very different inputs: an exact code someone copied from a bill or a report, and a loose description typed from memory.

The first version used fuzzy text matching: score every description by how similar it is to the query. That tolerated typos, but it was slow on half a million SNOMED CT concepts and noisy. A search for “breast cancer” would rank “Contusion of breast” near the top, because the words look similar even though the meaning is unrelated.

The current approach works in two stages:

  1. Word search first. A full-text index finds descriptions that contain every word of the query, in any order, with punctuation treated as spaces and “10mg” read as “10 mg”. This handles the large majority of real searches, and the results are the ones a person expects.
  2. Fuzzy matching only as a fallback, when word search finds nothing anywhere. That catches typos without letting near-misses crowd out real matches.

On a set of 26 real queries, this took total search time from about 21 seconds to about 3 seconds, and removed the near-miss noise from the top results.

A few other problems only showed up when results were checked against real counts. A single result limit across all systems let SNOMED CT’s size push everything else out: ICD-10-CM showed 5 of its 1,127 real matches for “diabetes”. Results are now grouped by code system, and each group has its own complete, linkable results page. Code-shaped queries such as “E11.9” also needed their own handling, so they would not fuzzy-match unrelated concepts that happened to contain a “9”.

Search runs inside Postgres, with no separate search server. For a project run by one person on one server, that is a deliberate choice: one less thing to operate, back up and pay for.

Value sets and how they change

Value sets are curated code lists, most of them published through the National Library of Medicine’s Value Set Authority Center (VSAC) for use in quality measures. XrefCodes loads them all, and users can also build their own, copy a published one as a starting point, and share lists with a team.

Quality measures are reported every year, so the common question is not “what is in this value set” but “what changed since last year”. Asking for an older version of a value set returns its old definition expanded against today’s code systems, which is not the same as the list that was published for that year.

The reliable history comes from the annual eCQM release manifests, which record exactly what each value set contained in each reporting year. XrefCodes stores those snapshots separately from the current value sets: about 2,600 of them, with around half a million member rows. Comparing two releases is then a matter of comparing two stored lists. The snapshots are kept apart so that search and the patient group builder only ever see current data.

From code lists to patients and SQL

Code lists describe conditions, tests and treatments; the questions analysts are asked are about patients. This part turns one into the other.

Patient groups and measures

A code list on its own does not answer a question about patients. “Adults with type 2 diabetes and no diagnosis of pregnancy” needs logic: which lists, combined how, over what time window, for whom.

XrefCodes offers two kinds of patient group:

  • A population: every patient, or every encounter, that has codes from some lists and doesn’t have codes from others. It is built as plain sentences in groups (“has any of… and doesn’t have any of…”), rather than as a boolean expression editor.
  • A measure, in the style of the electronic clinical quality measures (eCQMs) used in US reporting: an initial population, a denominator, exclusions, exceptions and a numerator, with an age range at the start of the measurement period. Criteria can be limited to a time window, and lab criteria can test a result value, optionally using only the most recent result. Time-based measures, such as the median time patients spend in the emergency department, are supported too.

A measure can start from a published eCQM, in which case XrefCodes fills in its value sets by role, read from the measure’s official logic package. The results are always labelled unofficial: they follow the structure of the published measure, but they are not the steward’s certified logic, and XrefCodes never claims they are.

One early bug was instructive. The first version resolved “has diabetes AND has hypertension” by intersecting the two code lists, which is almost always empty: no single code means both. The criteria have to be applied to patients, each against its own list. That is why the logic lives in generated SQL that runs against patient data, rather than in code-list arithmetic.

Generating SQL for a warehouse it never sees

This is where XrefCodes goes beyond a lookup tool, and where its main constraint applies: it is designed never to hold patient data or connect to anyone’s database. It only works with the shape of a warehouse, never its contents.

The flow has three parts.

1. Describe the warehouse. The user uploads a schema: a dbt catalog or schema file, an export from the database’s information schema, or CREATE TABLE statements. Only table names, column names and types are kept, and the original file is discarded after it is read. Uploads that appear to contain anything other than structure are refused.

2. Map it once. XrefCodes suggests which tables hold patients, diagnoses, procedures, lab results, medications and encounters, and which columns hold the patient ID, the code, the dates and the result values. The user confirms or corrects each suggestion. The mapping also records how codes are written in that warehouse: with or without the ICD-10 dot, which NDC format, whether a column says which code system each row uses. The result is a reusable data map.

3. Generate. For any patient group or code list, the user picks a data map, a SQL dialect, and either a dbt project or plain SQL.

Patient group who's in it Data map your tables → domains Code table every spelling: E11.9 · E119 Staging models your tables, one shape Criterion models patients matching each rule Cohort or measure model logic · populations · rate Translated per dialect Postgres · Snowflake · BigQuery · …
The generated project is layered the way a data engineer would write it by hand, with each step commented.

A few design choices are worth explaining.

  • A code table instead of long IN-lists. Every code is written out in every spelling warehouses commonly use: ICD-10 with and without the dot, NDC in its 11-digit and hyphenated forms. RxNorm ingredients are expanded to the drug products that contain them, and to their NDCs, if the data map says medications are stored that way. The matching logic then becomes a simple join, and formatting differences stop being a source of silently missed patients.
  • Written once, translated seven times. The SQL is written in one dialect and translated with an open-source SQL translator to Postgres, Snowflake, BigQuery, Databricks, Redshift, SQL Server and DuckDB. The places where dialects truly differ, such as date arithmetic and safe numeric conversion, are marked during generation and filled in per dialect.
  • A record of what went in. Every download lists the code system releases and value set versions it used, and any codes it left out and why. When a result is questioned six months later, the inputs can be traced.
  • Tested by running it. Generated projects are executed in DuckDB against synthetic patients with known answers, and every output is checked to parse in all seven dialects. A measure modelled on a real eCQM is run end to end in both DuckDB and Postgres.

Because the SQL runs in the user’s own warehouse, XrefCodes does not see patient rows and does not compute rates itself; it writes the query that does.

Keeping the data current

A code search tool is only as good as its last load, so updating has to be routine rather than a project.

The difficulty is that every publisher announces releases differently. Some offer an API that reports the latest version. Some only publish a web page that links to the newest file. Some release on a known schedule and are checked by hand. So each source has its own small check, and each check falls into one of three kinds.

Release check, every 7 days or "Check now" in the admin Release API SNOMED CT SNOMED → ICD map RxNorm eCQM update Publisher page ICD-10-CM ICD-10-PCS HCPCS CVX Schedule LOINC UDS manual NDC (30 days) VSAC (90 days) Status per source: loaded vs latest a failed check keeps its last result Email to administrators only when newly out of date Data sources dashboard Download & load · Reload Background job back up → load → log
Every source is checked the most direct way its publisher allows. A person always decides when to load.
Source How a new release is detected Usual cadence How it is loaded
SNOMED CT, and its ICD-10-CM map NLM’s public release API March and September Downloaded from NLM, then loaded
RxNorm NLM’s public release API Monthly Reloaded from NLM’s RxNav API
eCQM value set history The newest eCQM update manifest in VSAC Each May Reloaded from VSAC
ICD-10-CM, ICD-10-PCS The newest file listed on the CMS ICD-10 page Yearly, effective October 1 Downloaded from CMS, then loaded
HCPCS Level II The newest quarterly file on the CMS page January, April, July, October Downloaded from CMS, then loaded
CVX The newest change date in CDC’s vaccine table Whenever a code changes Downloaded from CDC, then loaded
NDC Directory No release numbers: flagged after 30 days FDA updates it daily Downloaded from FDA, then loaded
VSAC value sets Changes continuously: flagged after 90 days Continuous Re-synced from VSAC, one value set at a time
LOINC Release schedule Around February and August Downloaded by hand from the publisher
UDS measures Release schedule Each autumn Downloaded by hand, reviewed, then loaded

For sources on a schedule, the check records when the next release is expected and links to the publisher’s page, and a person does the rest.

The weekly check runs in the background worker, never inside a web request. One source failing to respond does not stop the others; the failed source keeps its previous result and shows the error. An email goes to the administrators only when a source becomes out of date, not every week that it stays so, which keeps the alerts worth reading.

Loading stays a human decision. From the dashboard, an administrator can download and load a release in one step, download it to review first, or reload an API-based source. Every load runs as a background job and starts with a full database backup, and loaders only ever add or update codes, never delete them.

Principles and where it stands

Principles that held up

Looking back over the build, a few principles shaped almost every decision:

  • Reference, not advice. Show what the official sources say, with their release and date, and do not present any code as the right answer for a patient or a claim.
  • No patient data. Schemas in, SQL out. The product is designed so that this holds by construction, not only by policy.
  • Publishers’ terms applied per code, on every page, export and generated file.
  • Boring infrastructure. One Django application, one Postgres database, one small server, server-rendered pages. Search stays in Postgres; background jobs use a table in the same database. Every extra service would be one more thing for one person to run.
  • Test what produces results. About 600 automated tests cover the patient-group logic, every loader (on sample files, never the live database), the schema parsers and the SQL generator. A bug there is the tool’s error, not the source’s.

Where it stands

XrefCodes is in a private beta, with access granted on request. Measure support is broad but deliberately labelled unofficial.

The core idea has held up from the first day: start from the official files, keep every code tied to its source and release, and make the path from a plain-language question to a runnable query as short as possible.


About the sources. XrefCodes is an independent project. It is not affiliated with or endorsed by the National Library of Medicine, CMS, CDC, FDA, HRSA, Regenstrief Institute, SNOMED International or the American Medical Association. LOINC® is a registered trademark of Regenstrief Institute, Inc. SNOMED® and SNOMED CT® are registered trademarks of SNOMED International. CPT® is a registered trademark of the American Medical Association. Code examples in this note are from ICD-10-CM, which is in the public domain. Nothing here is coding, billing or clinical advice; always check codes against the official sources.