Technical writing

CDC Drug Overdose Mortality: The Federal Database Behind the US Opioid Crisis

· 14 min read· AI Analytics
CDCDrug OverdoseOpioid CrisisMortalityFederal Data

In 2023, the CDC's National Center for Health Statistics recorded 107,543 drug overdose deaths in the United States. That number is provisional — final counts arrive roughly a year after the calendar year closes — but it marks the third consecutive year above 100,000. For context: 80,391 people died of overdoses in 2021, the first year the count crossed six figures. The number in 1999, when the CDC began tracking the modern epidemic, was 16,849.

Behind those numbers sits a federal data infrastructure spanning three CDC databases, thousands of death certificates processed through ICD-10 drug classification codes, provisional monthly estimates that arrive months before final counts, and a public query system covering every death in the United States since 1999. This guide explains how that infrastructure works, what it reveals about the three-wave opioid crisis and the fentanyl era, and how to query it programmatically.

Three waves, twenty-five years

The US overdose epidemic is typically described in three waves, each driven by a different substance entering the drug supply at scale. Understanding the wave structure is prerequisite to reading the data correctly — the ICD-10 codes that dominate each era shift dramatically, and cross-wave comparisons require care.

Wave 1: Prescription opioids (late 1990s–2010)

Purdue Pharma launched OxyContin in 1996 with marketing that claimed addiction risk below 1 percent for patients taking opioids for legitimate pain. That claim was false; the company later paid $634 million in criminal fines in 2007 for misbranding. But the marketing worked. Through the late 1990s and 2000s, pharmaceutical manufacturers, distributors, and prescribers built a legal pill supply vastly in excess of any plausible clinical need.

The DEA's quota system — which sets annual production limits for Schedule II controlled substances — accommodated massive increases in oxycodone and hydrocodone production throughout this period. Distributors shipped 76 billion oxycodone and hydrocodone pills to US pharmacies between 2006 and 2012 alone. Pill mills concentrated in Florida, Ohio, and West Virginia dispensed prescriptions with minimal medical justification. Mingo County, West Virginia — population roughly 26,000 — received enough pills to supply every resident with more than 200 oxycodone and hydrocodone tablets per year at the epidemic's peak.

Prescription opioid deaths peaked around 2010 at approximately 17,000 per year, coded in the mortality data primarily as natural and semisynthetic opioid deaths (ICD-10 T40.2 — oxycodone, hydrocodone, codeine). The CDC data for this era is relatively clean: most deaths involved a documented prescription opioid identified through standard toxicology.

Wave 2: Heroin (2010–2013)

As prescription opioids became harder to obtain — abuse-deterrent reformulations of OxyContin in 2010, expanding prescription drug monitoring programs, pill mill crackdowns in Florida and other states — people dependent on opioids shifted to heroin, which was cheaper and more available. Between 2010 and 2013, heroin deaths roughly tripled in the CDC mortality data.

The wave 2 mortality signal appears in ICD-10 code T40.1 (heroin). The geographic pattern in the CDC data shifted somewhat: heroin supply chains were better established in urban and suburban markets, so overdose deaths began diffusing from the rural Appalachian epicenter of wave 1 toward cities and suburbs in the Northeast, Midwest, and Pacific Northwest.

Wave 3: Synthetic opioids (2013–present)

Illicitly manufactured fentanyl began appearing in the US drug supply around 2013 and became the dominant driver of overdose mortality by 2016. Fentanyl is 50 to 100 times more potent than morphine by weight. At that potency, a quantity invisible to the naked eye can be lethal. Initial production came primarily from Chinese chemical manufacturers; following 2019 international treaty scheduling of fentanyl and its analogs, production shifted to Mexican cartels — primarily the Sinaloa Cartel and Jalisco New Generation Cartel — using precursor chemicals from India and China.

The fentanyl supply chain now contaminates the entire illicit drug market. It entered the heroin supply first, then began appearing in counterfeit pharmaceutical pills — fake M30 oxycodone tablets pressed with fentanyl content varying pill-to-pill from trace amounts to lethal doses. By 2022, synthetic opioid involvement appeared in roughly 50 percent of stimulant overdose deaths (cocaine and methamphetamine), reflecting fentanyl contamination of the stimulant supply.

In 2022, approximately 75,000 of the year's overdose deaths involved synthetic opioids — primarily fentanyl — making T40.4 the single most important field in the CDC overdose mortality dataset. Carfentanil, a fentanyl analog used as an elephant tranquilizer and roughly 100 times more potent than fentanyl itself, appears sporadically in toxicology reports. Xylazine — a veterinary sedative not classified as a controlled substance, not reversed by naloxone — has emerged as a common adulterant in the fentanyl supply in eastern US cities, causing characteristic skin wounds at injection sites and complicating overdose reversal.

CDC data infrastructure

Three primary CDC data sources cover drug overdose mortality. Each has different update frequency, geographic granularity, and coverage of drug-specific detail.

VSRR Provisional Drug Overdose Counts

The Vital Statistics Rapid Release (VSRR) program publishes provisional monthly overdose death counts at cdc.gov/nchs/nvss/vsrr/drug-overdose-data.htm. Final vital statistics data has an 8–12 month lag from the reference month to publication; VSRR reduces that to roughly 6 months by releasing provisional counts before all death certificates are fully coded and processed.

VSRR data is reported as 12-month rolling sums rather than single-month counts, which smooths seasonal variation and reduces the statistical noise inherent in provisional reporting. The dataset covers national and state-level counts (not county) broken down by drug category using ICD-10 cause-of-death codes. Drug category indicators include all opioids, synthetic opioids excluding methadone (T40.4), heroin (T40.1), natural and semisynthetic opioids (T40.2), methadone (T40.3), cocaine (T40.5), and stimulants including methamphetamine (T43.6).

Small counts are suppressed per NCHS data suppression policy — states with fewer than 10 deaths in a category in a given period show a suppressed value. The VSRR dataset includes both actual and predicted values; predicted values use modeling to estimate counts for states and periods with incomplete data, and are typically used when actual values are suppressed or not yet available.

The VSRR dataset is available as a flat file download and via the CDC's Socrata API at data.cdc.gov/NCHS/VSRR-Provisional-Drug-Overdose-Death-Counts/xkb8-kh2a. The Socrata endpoint supports standard SQL-style query parameters and pagination.

WONDER (Wide-ranging Online Data for Epidemiologic Research)

CDC WONDER at wonder.cdc.gov provides access to the complete death certificate record for every death in the United States from 1999 to the present (with a longer lag than VSRR). WONDER allows querying by year, month, state, county, age group, race/ethnicity, sex, and education level, returning counts and crude or age-adjusted rates per 100,000 population.

For drug overdose analysis, WONDER is queried using both the underlying cause of death and multiple cause of death codes. The underlying cause for a drug overdose death is typically X40–X44 (accidental drug poisoning), X60–X64 (intentional self-poisoning), or Y10–Y14 (undetermined intent). The drug-specific breakdown requires the multiple cause of death T-codes — these identify which substances were involved in the death, separate from the manner of death determination.

WONDER's primary limitation for bulk programmatic access is its interface: the system uses a WSDL-based web service rather than a REST API, and query results are suppressed when any cell contains fewer than 10 deaths. County-level analysis for small states or rare drug categories frequently encounters suppression. For county-level analysis, the CDC also publishes a Drug Overdose Mortality by State data file at data.cdc.gov covering death rates per 100,000 by state and drug category.

State-level drug category data file

The CDC publishes an annual flat file at data.cdc.gov with state-by-drug-category overdose death rates per 100,000 population covering 83,000-plus records. This file is directly downloadable and suitable for cross-state comparison analyses without needing to navigate the WONDER interface. Suppression applies to small states and rare drug categories, consistent with NCHS policy.

ICD-10 drug classification codes

Drug-specific overdose analysis depends on ICD-10 T-codes reported as multiple causes of death on death certificates. A single death may carry multiple T-codes if more than one substance was involved — polysubstance deaths are the rule rather than the exception in current overdose data. The critical codes:

  • T40.1 — Heroin. The primary wave 2 indicator, still significant in the fentanyl era as many heroin users now consume fentanyl-adulterated supply.
  • T40.2 — Natural and semisynthetic opioids (oxycodone, hydrocodone, codeine, oxymorphone). The wave 1 prescription opioid signal. Deaths involving T40.2 have declined since 2010 as prescription volumes dropped, but remain significant due to prescription opioid diversion and concurrent fentanyl involvement.
  • T40.3 — Methadone. Both illicit methadone and methadone prescribed for pain management (not methadone maintenance therapy for opioid use disorder). Tracked separately because methadone's long half-life creates distinct overdose pharmacology.
  • T40.4 — Other synthetic opioids (fentanyl, tramadol, tapentadol). This is the critical tracking field for the wave 3 synthetic opioid crisis. Fentanyl is not explicitly named in ICD-10 T40.4; its presence is inferred from toxicology. T40.4 deaths have grown from under 10,000 in 2013 to over 75,000 in 2022.
  • T40.5 — Cocaine. Deaths involving cocaine have surged since 2015 in part because cocaine users are increasingly exposed to fentanyl-contaminated supply — deaths coded T40.5 frequently also carry T40.4.
  • T43.6 — Psychostimulants with abuse potential, primarily methamphetamine. West and Pacific states have higher methamphetamine death rates; the co-occurrence of T43.6 and T40.4 (meth plus fentanyl) reflects contamination of the stimulant supply rather than intentional polysubstance use.
  • T50.9 — Other and unspecified drugs. Deaths where toxicology was incomplete or the specific substance was not identified. High T50.9 rates in rural counties with limited medical examiner capacity represent an undercount of drug-specific mortality.

The death certificate attribution process introduces significant measurement challenges. Medical examiners and coroners vary in their toxicology testing capacity; rural and under-resourced jurisdictions may not test for the full panel of synthetic opioids and adulterants. Xylazine, for example, is not included in standard immunoassay toxicology panels and requires specific testing; its presence in the drug supply is almost certainly undercounted in ICD-10 coded mortality data. The 2023 introduction of xylazine as a reportable substance in some state surveillance systems has begun to surface the scale of this gap.

Geographic patterns

Overdose death rates per 100,000 population vary dramatically across states and have shifted considerably across the three waves. In 2022, West Virginia led the nation at roughly 80 deaths per 100,000 population — a rate approximately five times the national average. Kentucky, Tennessee, Louisiana, Ohio, and the District of Columbia also ranked among the highest-rate states.

The Appalachian concentration reflects wave 1 legacy: coal country communities with high rates of occupational injury, disability, and unemployment were aggressively targeted by pharmaceutical marketing in the late 1990s. Pill mills in Florida, West Virginia, and Ohio funneled prescription opioids into these communities. The resulting population with established opioid dependence became the initial cohort for waves 2 and 3.

The current fentanyl crisis is geographically more diffuse. Fentanyl supply chains run through southwest border ports of entry and distribution networks that cover urban and suburban markets nationally. States that had relatively low overdose rates in the prescription opioid era — including western states and New England — now show elevated synthetic opioid mortality. New Hampshire and Connecticut have some of the highest fentanyl-specific death rates in the country despite not being opioid prescription hotspots.

Methamphetamine mortality shows a distinct geographic pattern. Western and Pacific states — California, Oregon, Washington, Arizona, Nevada — have historically higher methamphetamine death rates, reflecting established West Coast supply chains dating to the domestic meth production era. Mexican cartel production of cheap, high-purity methamphetamine has expanded this geography eastward while simultaneously driving down street prices.

Fentanyl supply chain

Illicitly manufactured fentanyl's supply chain context matters for interpreting CDC mortality trends because changes upstream — in precursor chemical availability, cartel production capacity, and distribution logistics — translate directly into mortality data with a lag measured in months.

Before 2019, the primary source of fentanyl precursor chemicals was Chinese chemical manufacturers, often operating legally under Chinese law but shipping to criminal networks. In 2019, following sustained US diplomatic pressure, China scheduled fentanyl and approximately 1,400 fentanyl analogs under international law. This disrupted the direct China-to-US fentanyl pipeline but accelerated the shift to Mexico as the primary production hub.

Mexican cartels — primarily the Sinaloa Cartel and Jalisco New Generation Cartel — now produce the substantial majority of fentanyl entering the US market. Precursor chemicals arrive from India and China into Mexico for synthesis. Finished product crosses the US-Mexico border in commercial cargo and through ports of entry, where the volume conceals detection.

Counterfeit pharmaceutical pills pressed with illicit fentanyl — particularly fake M30 oxycodone tablets — have become a primary distribution vector, particularly for younger users who may believe they are taking a pharmaceutical product. DEA testing of seized M30 tablets found that approximately 6 in 10 contain a potentially lethal dose of fentanyl; pill-to-pill variation in fentanyl content means that even users with high tolerance cannot calibrate dose.

The combination of xylazine and fentanyl — known as “tranq dope” — presents a distinct harm reduction challenge: xylazine is a veterinary alpha-2 adrenergic agonist, not an opioid receptor agonist, so naloxone does not reverse its sedative effects. A user who overdoses on a xylazine-fentanyl mixture may have the fentanyl component reversed by naloxone but remain sedated from xylazine; without prompt emergency medical care, death can occur from respiratory depression or airway obstruction.

Naloxone, harm reduction, and treatment data

The federal overdose data infrastructure extends beyond mortality into prevention and treatment surveillance. SAMHSA's Behavioral Health Services Information System tracks naloxone distribution through opioid treatment programs. The CDC publishes MMWR reports on naloxone co-prescribing rates alongside high-dose opioid prescriptions. State overdose surveillance systems — aggregated through the OD Map partnership — provide near-real-time nonfatal overdose counts in participating jurisdictions.

As of 2022, more than 1.6 million people in the United States inject drugs, per CDC estimates. Syringe service programs (SSPs) — now eligible for federal funding following the 2018 repeal of the longstanding SSP federal funding prohibition — distribute naloxone and fentanyl test strips alongside sterile injection equipment. Fentanyl test strips were classified as drug paraphernalia under most state laws until a wave of state-level exemptions beginning around 2021; their legal status varies by state and affects distribution capacity.

Treatment access remains the most significant gap in the federal data picture. Medications for opioid use disorder (MOUD) include buprenorphine (a partial opioid agonist, Schedule III, historically requiring a DEA waiver that was eliminated by the Mainstreaming Addiction Treatment Act in 2023), methadone (full agonist, dispensed only through DEA-licensed opioid treatment programs), and extended-release naltrexone (opioid antagonist, monthly injection). Fewer than 20 percent of people with opioid use disorder receive any form of MOUD, according to SAMHSA national survey data. The treatment gap is not primarily a data problem — it reflects insurance coverage, stigma, provider availability, and program accessibility — but the federal datasets tracking both overdose deaths and treatment utilization put its scale in sharp relief.

Purdue Pharma and the legal reckoning

The legal proceedings that followed the prescription opioid crisis produced the largest pharmaceutical liability settlements in US history and generated substantial public data disclosure in the process — most notably the DEA ARCOS transaction records released through the opioid MDL discovery process.

Purdue Pharma filed for bankruptcy in 2019; a 2022 DOJ settlement imposed $8.34 billion in civil and criminal liability. The Sackler family, which owned Purdue, agreed to personal payments of $6 billion. McKinsey & Company, which consulted to Purdue on its marketing strategy, settled for $600 million. The three largest pharmaceutical distributors — McKesson, AmerisourceBergen, and Cardinal Health — settled with states for $21 billion over 18 years. Johnson & Johnson settled for $5 billion; major pharmacy chains (CVS, Walgreens, Walmart) for $13.8 billion; Mallinckrodt for $1.7 billion; Endo International for $450 million. Total opioid-related legal settlements exceed $55 billion across all defendants as of 2024.

The National Opioid Abatement Trust, funded by settlement proceeds, distributes money to states and localities for prevention, treatment, and recovery programs. Settlement spending data is publicly tracked by the Opioid Settlement Tracker project and represents an emerging data layer on top of the CDC mortality statistics — pairing death toll with remediation investment by jurisdiction.

VSRR API and Python analysis

The CDC VSRR provisional overdose dataset is accessible via the Socrata API at data.cdc.gov. The endpoint at /resource/xkb8-kh2a.json accepts standard Socrata SoQL query parameters for filtering by state, indicator, period type, and year. Key fields: state_name, year, month, period (12-Month Ending, Month, Year-to-Date), indicator, data_value, predicted_value, and data_value_flag (suppression indicator). The default page size is 1,000 rows; pagination via \$limit and \$offset is required for full downloads.

The following script fetches 12-month rolling synthetic opioid death counts by state, joins to Census population estimates to compute death rates per 100,000, ranks all states, and then pulls national monthly opioid versus stimulant trends for 2019–2023 to show the diverging trajectories across the wave 3 period.

import requests
import pandas as pd

# -------------------------------------------------------
# CDC VSRR Provisional Drug Overdose Mortality Analysis
#
# This script:
#   1. Fetches 12-month rolling synthetic opioid death counts
#      by state from the CDC VSRR Socrata API
#   2. Joins to Census 2022 population estimates to compute
#      death rates per 100,000 population
#   3. Ranks all states by synthetic opioid death rate
#   4. Fetches national monthly opioid vs. stimulant trends
#      for 2019-2023 to show diverging/converging trajectories
# -------------------------------------------------------

VSRR_ENDPOINT = (
    "https://data.cdc.gov/resource/xkb8-kh2a.json"
)

# Census 2022 state population estimates (abbreviated)
# Full list from: https://api.census.gov/data/2022/pep/population
CENSUS_POP_2022 = {
    "AK": 733583,  "AL": 5074296,  "AR": 3045637,  "AZ": 7359197,
    "CA": 39029342, "CO": 5839926, "CT": 3626205,  "DC": 671803,
    "DE": 1018396,  "FL": 22244823, "GA": 10912876, "HI": 1440196,
    "IA": 3200517,  "ID": 1939033,  "IL": 12582032, "IN": 6833037,
    "KS": 2937150,  "KY": 4512310,  "LA": 4590241,  "MA": 6981974,
    "MD": 6164661,  "ME": 1385340,  "MI": 10034113, "MN": 5717184,
    "MO": 6177957,  "MS": 2940057,  "MT": 1122867,  "NC": 10698973,
    "ND": 779261,   "NE": 1967923,  "NH": 1395231,  "NJ": 9261699,
    "NM": 2113344,  "NV": 3177772,  "NY": 19677151, "OH": 11756058,
    "OK": 4019800,  "OR": 4240137,  "PA": 12972008, "RI": 1093734,
    "SC": 5282634,  "SD": 909824,   "TN": 7051339,  "TX": 30029572,
    "UT": 3380800,  "VA": 8683619,  "VT": 647464,   "WA": 7785786,
    "WI": 5892539,  "WV": 1775156,  "WY": 581381,
}

# State abbreviation to full name mapping (subset)
STATE_NAMES = {
    "West Virginia": "WV", "Ohio": "OH", "Kentucky": "KY",
    "Tennessee": "TN", "Louisiana": "LA", "District of Columbia": "DC",
    "Delaware": "DE", "Maryland": "MD", "Pennsylvania": "PA",
    "Missouri": "MO", "Indiana": "IN", "Michigan": "MI",
    "Connecticut": "CT", "Maine": "ME", "New Hampshire": "NH",
    "Rhode Island": "RI", "Massachusetts": "MA", "New Mexico": "NM",
    "Nevada": "NV", "Colorado": "CO", "Vermont": "VT",
    "Virginia": "VA", "Arizona": "AZ", "New Jersey": "NJ",
}


def fetch_vsrr_paginated(params: dict, page_size: int = 1000) -> list[dict]:
    """Fetch all records from a CDC VSRR Socrata endpoint using offset pagination."""
    records = []
    offset = 0
    while True:
        paged = {**params, "$limit": page_size, "$offset": offset}
        resp = requests.get(VSRR_ENDPOINT, params=paged, timeout=60)
        resp.raise_for_status()
        batch = resp.json()
        if not batch:
            break
        records.extend(batch)
        if len(batch) < page_size:
            break
        offset += page_size
    return records


# -------------------------------------------------------
# Step 1: Fetch 12-month rolling synthetic opioid counts
#         by state (most recent available period)
# -------------------------------------------------------
print("Fetching 12-month synthetic opioid death counts by state...")

synth_params = {
    "$where": (
        "indicator='Synthetic opioids, excl. methadone (T40.4)' "
        "AND period='12-Month Ending' "
        "AND state != 'US'"
    ),
    "$order": "year DESC, month DESC",
}
synth_records = fetch_vsrr_paginated(synth_params)
synth_df = pd.DataFrame(synth_records)

# Keep only the most recent 12-month period per state
synth_df["data_value"] = pd.to_numeric(synth_df.get("data_value", pd.NA), errors="coerce")
synth_df["predicted_value"] = pd.to_numeric(synth_df.get("predicted_value", pd.NA), errors="coerce")
synth_df["year"] = pd.to_numeric(synth_df.get("year", pd.NA), errors="coerce")
synth_df["month"] = pd.to_numeric(synth_df.get("month", pd.NA), errors="coerce")

# Use predicted_value where data_value is suppressed/missing
synth_df["deaths"] = synth_df["data_value"].fillna(synth_df["predicted_value"])

latest_period = synth_df.sort_values(["year", "month"], ascending=False).drop_duplicates("state_name")

# -------------------------------------------------------
# Step 2: Join to Census populations and compute rate
# -------------------------------------------------------
def get_abbr(state_name: str) -> str:
    """Map full state name to 2-letter abbreviation."""
    return STATE_NAMES.get(state_name, state_name[:2].upper())

latest_period = latest_period.copy()
latest_period["abbr"] = latest_period["state_name"].apply(get_abbr)
latest_period["pop_2022"] = latest_period["abbr"].map(CENSUS_POP_2022)
latest_period["rate_per_100k"] = (
    (latest_period["deaths"] / latest_period["pop_2022"]) * 100_000
).round(1)

# -------------------------------------------------------
# Step 3: Rank states by synthetic opioid death rate
# -------------------------------------------------------
ranked = (
    latest_period[["state_name", "deaths", "pop_2022", "rate_per_100k"]]
    .dropna(subset=["rate_per_100k"])
    .sort_values("rate_per_100k", ascending=False)
    .reset_index(drop=True)
)
ranked.index += 1

period_label = latest_period[["year", "month"]].dropna().iloc[0]
print(f"\n12-Month Period Ending {int(period_label['month'])}/{int(period_label['year'])}")
print("Synthetic Opioid (T40.4) Death Rate per 100,000 — All States Ranked")
print("-" * 65)
print(f"{'Rank':<6} {'State':<28} {'Deaths':>8} {'Rate/100k':>10}")
print("-" * 65)
for rank, row in ranked.iterrows():
    print(
        f"{rank:<6} {row['state_name']:<28} "
        f"{int(row['deaths']):>8,} {row['rate_per_100k']:>10.1f}"
    )

# -------------------------------------------------------
# Step 4: National monthly trend — opioids vs. stimulants
#         2019-2023 (12-month rolling, national level)
# -------------------------------------------------------
print("\nFetching national monthly opioid vs. stimulant trend data (2019-2023)...")

trend_params = {
    "$where": (
        "state_name='United States' "
        "AND period='12-Month Ending' "
        "AND (indicator='Opioids (T40.0-T40.4,T40.6)' "
        "     OR indicator='Stimulants, incl. methamphetamine (T43.6x, T43.62)' "
        "     OR indicator='Cocaine (T40.5)')"
        "AND year >= '2019' AND year <= '2023'"
    ),
    "$order": "year ASC, month ASC",
}
trend_records = fetch_vsrr_paginated(trend_params)
trend_df = pd.DataFrame(trend_records)
trend_df["data_value"] = pd.to_numeric(trend_df.get("data_value", pd.NA), errors="coerce")
trend_df["predicted_value"] = pd.to_numeric(trend_df.get("predicted_value", pd.NA), errors="coerce")
trend_df["deaths"] = trend_df["data_value"].fillna(trend_df["predicted_value"])
trend_df["year"] = pd.to_numeric(trend_df["year"], errors="coerce")
trend_df["month"] = pd.to_numeric(trend_df["month"], errors="coerce")
trend_df["period_label"] = (
    trend_df["year"].astype(int).astype(str)
    + "-"
    + trend_df["month"].astype(int).apply(lambda m: f"{m:02d}")
)

pivot = trend_df.pivot_table(
    index="period_label",
    columns="indicator",
    values="deaths",
    aggfunc="first",
).sort_index()

# Shorten column headers for display
pivot.columns = [c.split(" ")[0] for c in pivot.columns]
pivot = pivot.rename(columns={
    "Opioids": "Opioids",
    "Stimulants,": "Stimulants",
    "Cocaine": "Cocaine",
})

print("\nNational 12-Month Rolling Deaths: Opioids vs. Stimulants vs. Cocaine")
print("-" * 55)
print(f"{'Period':<12} {'Opioids':>10} {'Stimulants':>12} {'Cocaine':>10}")
print("-" * 55)
for period, row in pivot.iterrows():
    opioids = f"{int(row.get('Opioids', 0)):,}" if pd.notna(row.get("Opioids")) else "  n/a"
    stimulants = f"{int(row.get('Stimulants', 0)):,}" if pd.notna(row.get("Stimulants")) else "  n/a"
    cocaine = f"{int(row.get('Cocaine', 0)):,}" if pd.notna(row.get("Cocaine")) else "  n/a"
    print(f"{period:<12} {opioids:>10} {stimulants:>12} {cocaine:>10}")

A note on indicator string matching: the exact indicator strings in the VSRR dataset have changed across CDC data releases. The string “Synthetic opioids, excl. methadone (T40.4)” is the current canonical form, but earlier data vintages may use slightly different wording. When building production pipelines against this endpoint, querying for all indicator values first and then filtering locally is more robust than hard-coding indicator strings in the API query.

For county-level analysis, WONDER is the primary resource but requires navigating the browser interface or using R's wonder package for programmatic access. The flat file available at data.cdc.gov covering state-by-drug-category rates is the more practical option for cross-state comparisons without WONDER's suppression and interface constraints.

For the DOL Form 5500 pension fund data — another large federal dataset with systematic under-reporting challenges and complex entity relationships: DOL Form 5500: The Federal Database Behind $12 Trillion in US Pension Assets →

For the DEA ARCOS opioid distribution data that captures the upstream prescription pill supply feeding into wave 1 overdose mortality patterns: 380 million transactions: indexing the DEA's ARCOS opioid distribution data →