<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE article PUBLIC "-//NLM//DTD Journal Publishing DTD v2.0 20040830//EN" "journalpublishing.dtd"><article xmlns:mml="http://www.w3.org/1998/Math/MathML" xmlns:xlink="http://www.w3.org/1999/xlink" dtd-version="2.0" xml:lang="en" article-type="research-article"><front><journal-meta><journal-id journal-id-type="nlm-ta">J Med Internet Res</journal-id><journal-id journal-id-type="publisher-id">jmir</journal-id><journal-id journal-id-type="index">1</journal-id><journal-title>Journal of Medical Internet Research</journal-title><abbrev-journal-title>J Med Internet Res</abbrev-journal-title><issn pub-type="epub">1438-8871</issn><publisher><publisher-name>JMIR Publications</publisher-name><publisher-loc>Toronto, Canada</publisher-loc></publisher></journal-meta><article-meta><article-id pub-id-type="publisher-id">v28i1e90954</article-id><article-id pub-id-type="doi">10.2196/90954</article-id><article-categories><subj-group subj-group-type="heading"><subject>Tutorial</subject></subj-group></article-categories><title-group><article-title>Linking Dispense Data to Electronic Health Orders: Tutorial for Querying Commercial Pharmacy Databases to Support Systemwide Quality Improvement</article-title></title-group><contrib-group><contrib contrib-type="author" corresp="yes" equal-contrib="yes"><name name-style="western"><surname>Michaels</surname><given-names>Benjamin</given-names></name><degrees>MIDS, PharmD</degrees><xref ref-type="aff" rid="aff1">1</xref><xref ref-type="fn" rid="equal-contrib1">*</xref></contrib><contrib contrib-type="author" equal-contrib="yes"><name name-style="western"><surname>Pourian</surname><given-names>Jessica</given-names></name><degrees>MD</degrees><xref ref-type="aff" rid="aff2">2</xref><xref ref-type="fn" rid="equal-contrib1">*</xref></contrib></contrib-group><aff id="aff1"><institution>Department of Pharmacy, University of California, San Francisco</institution><addr-line>1500 Owens Street</addr-line><addr-line>San Francisco</addr-line><addr-line>CA</addr-line><country>United States</country></aff><aff id="aff2"><institution>Division of Clinical Informatics and Digital Transformation, Department of Pediatrics, University of California, San Francisco</institution><addr-line>San Francisco</addr-line><addr-line>CA</addr-line><country>United States</country></aff><contrib-group><contrib contrib-type="editor"><name name-style="western"><surname>Coristine</surname><given-names>Andrew</given-names></name></contrib></contrib-group><contrib-group><contrib contrib-type="reviewer"><name name-style="western"><surname>Palmsten</surname><given-names>Kristin</given-names></name></contrib><contrib contrib-type="reviewer"><name name-style="western"><surname>May O'Donnell</surname><given-names>R</given-names></name></contrib></contrib-group><author-notes><corresp>Correspondence to Benjamin Michaels, MIDS, PharmD, Department of Pharmacy, University of California, San Francisco, 1500 Owens Street, San Francisco, CA, 94158, United States, 1 513 658 0104; <email>Benjamin.michaels@ucsf.edu</email></corresp><fn fn-type="equal" id="equal-contrib1"><label>*</label><p>all authors contributed equally</p></fn></author-notes><pub-date pub-type="collection"><year>2026</year></pub-date><pub-date pub-type="epub"><day>6</day><month>10</month><year>2026</year></pub-date><volume>28</volume><elocation-id>e90954</elocation-id><history><date date-type="received"><day>12</day><month>01</month><year>2026</year></date><date date-type="rev-recd"><day>03</day><month>09</month><year>2026</year></date><date date-type="accepted"><day>09</day><month>09</month><year>2026</year></date></history><copyright-statement>&#x00A9; Benjamin Michaels, Jessica Pourian. Originally published in the Journal of Medical Internet Research (<ext-link ext-link-type="uri" xlink:href="https://www.jmir.org">https://www.jmir.org</ext-link>), 6.10.2026. </copyright-statement><copyright-year>2026</copyright-year><license license-type="open-access" xlink:href="https://creativecommons.org/licenses/by/4.0/"><p>This is an open-access article distributed under the terms of the Creative Commons Attribution License (<ext-link ext-link-type="uri" xlink:href="https://creativecommons.org/licenses/by/4.0/">https://creativecommons.org/licenses/by/4.0/</ext-link>), which permits unrestricted use, distribution, and reproduction in any medium, provided the original work, first published in the Journal of Medical Internet Research (ISSN 1438-8871), is properly cited. The complete bibliographic information, a link to the original publication on <ext-link ext-link-type="uri" xlink:href="https://www.jmir.org/">https://www.jmir.org/</ext-link>, as well as this copyright and license information must be included.</p></license><self-uri xlink:type="simple" xlink:href="https://www.jmir.org/2026/1/e90954"/><abstract><sec><title>Background</title><p>Assessing medication adherence is central to quality care, yet linking electronic health record (EHR) medication orders to outpatient pharmacy dispense data remains technically complex.</p></sec><sec><title>Objective</title><p>This study aimed to present a generalized, reproducible tutorial for linking EHR medication orders to pharmacy dispense data that can be used to assess medication dispense proportions.</p></sec><sec sec-type="methods"><title>Methods</title><p>We developed and validated a structured query approach to link EHR medication orders to external pharmacy dispense data using patient identifiers, medication-level identifiers, pharmacy identifiers, and temporal constraints. The tutorial emphasizes key design decisions, including handling multiple triggering events, deduplication across vendors, and managing formulation changes. A retrospective cohort of pediatric acute otitis media encounters (January 1, 2021, to January 1, 2024) was used as an illustrative example.</p></sec><sec sec-type="results"><title>Results</title><p>Overall, 98.3% (302/307) of pharmacies in the cohort returned at least 1 dispense record during the study period and were therefore classified as reporting pharmacies. Among 3404 orders, 2616 (76.9%) had a recorded dispense.</p></sec><sec sec-type="conclusions"><title>Conclusions</title><p>EHR-integrated pharmacy data provide a feasible, timely proxy for assessing medication adherence. This tutorial provides a scalable framework for linking EHR and pharmacy data for medication adherence studies, while highlighting key methodological considerations for SQL coding.</p></sec></abstract><kwd-group><kwd>electronic health record</kwd><kwd>pharmacy information systems</kwd><kwd>quality improvement</kwd><kwd>clinical informatics</kwd><kwd>health information exchange</kwd><kwd>drug prescriptions</kwd></kwd-group></article-meta></front><body><sec id="s1" sec-type="intro"><title>Introduction</title><p>Medication adherence is a critical determinant of clinical outcomes. Understanding and quantifying medication use allow clinicians to tailor care, as nonadherence has been associated with increased health care use and morbidity [<xref ref-type="bibr" rid="ref1">1</xref>].</p><p>Medication adherence is often evaluated using patient surveys, which can be cumbersome, prone to recall bias, and limited in their ability to capture objective data [<xref ref-type="bibr" rid="ref1">1</xref>,<xref ref-type="bibr" rid="ref2">2</xref>]. Prescription claims data provide a validated method for assessing medication adherence, including calculation of the proportion of days covered, but may be subject to delays and may exclude patients who are uninsured or who pay out of pocket [<xref ref-type="bibr" rid="ref2">2</xref>-<xref ref-type="bibr" rid="ref4">4</xref>].</p><p>An alternative is to use noninstitutional medication dispense data, which are often extracted, transformed, and loaded into electronic health records (EHRs) via third-party vendors [<xref ref-type="bibr" rid="ref5">5</xref>]. Two of the most common third-party vendors are DrFirst [<xref ref-type="bibr" rid="ref6">6</xref>] and Surescripts [<xref ref-type="bibr" rid="ref7">7</xref>]. The data from these vendors have discrete elements that can be used to link back to the EHR medication order [<xref ref-type="bibr" rid="ref8">8</xref>]. Using these resources allows for near real-time access to dispense data. By leveraging commercial pharmacy databases, dispense data can also be matched one-to-one with medication orders, enabling large-scale studies of medication adherence patterns across populations. Previous research has demonstrated that these data capture medication dispenses for the majority of patients and may be used for quality improvement (QI) projects assessing adherence [<xref ref-type="bibr" rid="ref2">2</xref>,<xref ref-type="bibr" rid="ref5">5</xref>,<xref ref-type="bibr" rid="ref9">9</xref>,<xref ref-type="bibr" rid="ref10">10</xref>]. This methodology is particularly valuable for epidemiologic studies because it directly links clinical encounters to prescription dispenses, allowing differentiation between true medication nonadherence and cases in which a prescription was not renewed&#x2014;an important limitation of claims-based data [<xref ref-type="bibr" rid="ref4">4</xref>,<xref ref-type="bibr" rid="ref11">11</xref>]. Importantly, these data include patients without insurance or those who may pay out of pocket&#x2014;the dispense is recorded in these databases if the pharmacy dispenses the medication, regardless of the payment method.</p><p>We began exploring this method during a QI project at our institution examining the use of watch-and-wait (also known as &#x201C;delayed&#x201D;) antibiotic prescribing for pediatric acute otitis media (AOM) in the outpatient setting. Delayed prescribing&#x2014;referred to as a safety net antibiotic prescription (SNAP) at our institution&#x2014;is challenging to study because claims data and patient surveys alone cannot reliably determine whether or when a prescribed SNAP is dispensed. To address this, we linked clinical encounters to pharmacy dispense data to assess the time to dispense from the encounter.</p><p>In this tutorial, we present a generalizable approach for linking EHR prescribing data with pharmacy dispense data, with a focus on reproducible, SQL-based data engineering methods that can be adapted across institutions regardless of the EHR system. A separate component of our prior work used a large language model to distinguish SNAPs from antibiotics intended for immediate use; that work has been published elsewhere and is not covered here [<xref ref-type="bibr" rid="ref12">12</xref>,<xref ref-type="bibr" rid="ref13">13</xref>]. For the purposes of this tutorial, we focused on the antibiotics that were meant to start immediately (not SNAPs), as they were intended to be dispensed and used on the day of the encounter, and thus have higher dispense proportions than SNAPs and should be more in line with other, more typically used medications that the reader may be interested in evaluating. For these reasons, we believe these prescriptions provide a better illustrative example for the SQL methods described herein and for what the reader may anticipate in terms of dispense rates for their own project.</p></sec><sec id="s2"><title>Tutorial</title><p>This section is structured as a step-by-step guide to linking EHR medication orders with external pharmacy dispense data, using a retrospective study of pediatric antibiotics for AOM as an illustrative case.</p><sec id="s2-1"><title>Step 1: Define the Study Population and Unit of Analysis</title><sec id="s2-1-1"><title>Case Study: Pediatric AOM Cohort</title><p>Before linking the orders to the dispense history, you must consider the granularity of the data that you are starting with alongside the goal. For this example, the unit is the medication order, not the patient. This allows for the tracking of individual prescription lifecycles from order to fulfillment. Depending on your individual use case, you may want the data to be pulled and aggregated at the patient, department, facility, or another level.</p><p>For our use case, we did not assess medication dispense at the patient level across multiple encounters, though this is certainly an option for future studies.</p></sec><sec id="s2-1-2"><title>Case Study Example</title><p>We included outpatient and emergency department encounters for pediatric patients (aged 6 mo to &#x003C;18 y) diagnosed with AOM using <italic>International Classification of Diseases</italic>, Tenth Revision, Clinical Modification (ICD-10) codes H65, H66, and H67 [<xref ref-type="bibr" rid="ref14">14</xref>,<xref ref-type="bibr" rid="ref15">15</xref>], between January 1, 2021, and January 1, 2024. The final cohort consisted of 3404 antibiotic orders for amoxicillin, amoxicillin-clavulanate, or cefdinir. An attrition diagram describing the encounter selection is in <xref ref-type="supplementary-material" rid="app1">Multimedia Appendix 1</xref>.</p><p>The included 3404 encounters were distributed among 2930 unique patients. Of these patients, 368 had multiple encounters, contributing a total of 842 encounters, with 2 to 6 encounters per patient (<xref ref-type="supplementary-material" rid="app2">Multimedia Appendix 2</xref>). A description of the demographics for these 3404 encounters is provided in <xref ref-type="table" rid="table1">Table 1</xref>.</p><p>Because this study was restricted to children in California, where pediatric health coverage is available through Medi-Cal regardless of their parents&#x2019; employment or immigration status, nearly all patients in the cohort were insured through either public or private insurance.</p><table-wrap id="t1" position="float"><label>Table 1.</label><caption><p>Encounter population (N=3404)<sup><xref ref-type="table-fn" rid="table1fn1">a</xref></sup>.</p></caption><table id="table1" frame="hsides" rules="groups"><thead><tr><td align="left" valign="bottom">Category</td><td align="left" valign="bottom">Overall, n (%)</td></tr></thead><tbody><tr><td align="left" valign="top" colspan="2">Sex</td></tr><tr><td align="left" valign="top"><named-content content-type="indent">&#x00A0;&#x00A0;&#x00A0;&#x00A0;</named-content>Female</td><td align="char" char="." valign="top">1498 (44.0)</td></tr><tr><td align="left" valign="top"><named-content content-type="indent">&#x00A0;&#x00A0;&#x00A0;&#x00A0;</named-content>Male</td><td align="left" valign="top">1906 (56.0)</td></tr><tr><td align="left" valign="top" colspan="2">Race</td></tr><tr><td align="left" valign="top"><named-content content-type="indent">&#x00A0;&#x00A0;&#x00A0;&#x00A0;</named-content>Asian<named-content content-type="indent">&#x00A0;&#x00A0;&#x00A0;&#x00A0;</named-content></td><td align="left" valign="top">397 (11.7)</td></tr><tr><td align="left" valign="top"><named-content content-type="indent">&#x00A0;&#x00A0;&#x00A0;&#x00A0;</named-content>Black</td><td align="left" valign="top">535 (15.7)</td></tr><tr><td align="left" valign="top"><named-content content-type="indent">&#x00A0;&#x00A0;&#x00A0;&#x00A0;</named-content>Declined/unknown</td><td align="left" valign="top">66 (1.9)</td></tr><tr><td align="left" valign="top"><named-content content-type="indent">&#x00A0;&#x00A0;&#x00A0;&#x00A0;</named-content>Mixed</td><td align="left" valign="top">299 (8.8)</td></tr><tr><td align="left" valign="top"><named-content content-type="indent">&#x00A0;&#x00A0;&#x00A0;&#x00A0;</named-content>Native</td><td align="left" valign="top">21 (0.6)</td></tr><tr><td align="left" valign="top"><named-content content-type="indent">&#x00A0;&#x00A0;&#x00A0;&#x00A0;</named-content>Other</td><td align="left" valign="top">1436 (42.2)</td></tr><tr><td align="left" valign="top"><named-content content-type="indent">&#x00A0;&#x00A0;&#x00A0;&#x00A0;</named-content>White</td><td align="left" valign="top">650 (19.1)</td></tr><tr><td align="left" valign="top" colspan="2">Clinic type</td></tr><tr><td align="left" valign="top"><named-content content-type="indent">&#x00A0;&#x00A0;&#x00A0;&#x00A0;</named-content>Emergency room</td><td align="left" valign="top">2015 (59.2)</td></tr><tr><td align="left" valign="top"><named-content content-type="indent">&#x00A0;&#x00A0;&#x00A0;&#x00A0;</named-content>Outpatient</td><td align="left" valign="top">1389 (40.8)</td></tr><tr><td align="left" valign="top" colspan="2">Language</td></tr><tr><td align="left" valign="top"><named-content content-type="indent">&#x00A0;&#x00A0;&#x00A0;&#x00A0;</named-content>English</td><td align="left" valign="top">2547 (74.8)</td></tr><tr><td align="left" valign="top"><named-content content-type="indent">&#x00A0;&#x00A0;&#x00A0;&#x00A0;</named-content>Other</td><td align="left" valign="top">857 (25.2)</td></tr><tr><td align="left" valign="top" colspan="2">Age, y</td></tr><tr><td align="left" valign="top"><named-content content-type="indent">&#x00A0;&#x00A0;&#x00A0;&#x00A0;</named-content>6 mo to &#x003C;1 y</td><td align="left" valign="top">756 (22.2)</td></tr><tr><td align="char" char="." valign="top"><named-content content-type="indent">&#x00A0;&#x00A0;&#x00A0;&#x00A0;</named-content>1 to &#x003C;1.5</td><td align="left" valign="top">373 (11.0)</td></tr><tr><td align="char" char="." valign="top"><named-content content-type="indent">&#x00A0;&#x00A0;&#x00A0;&#x00A0;</named-content>1.5 to &#x003C;2</td><td align="left" valign="top">234 (6.9)</td></tr><tr><td align="char" char="." valign="top"><named-content content-type="indent">&#x00A0;&#x00A0;&#x00A0;&#x00A0;</named-content>2 to &#x003C;5</td><td align="left" valign="top">1127 (33.1)</td></tr><tr><td align="char" char="." valign="top"><named-content content-type="indent">&#x00A0;&#x00A0;&#x00A0;&#x00A0;</named-content>5 to &#x003C;10</td><td align="left" valign="top">690 (20.3)</td></tr><tr><td align="char" char="." valign="top"><named-content content-type="indent">&#x00A0;&#x00A0;&#x00A0;&#x00A0;</named-content>10 to &#x003C;18</td><td align="left" valign="top">224 (6.6)</td></tr><tr><td align="left" valign="top" colspan="2">Insurance type</td></tr><tr><td align="left" valign="top"><named-content content-type="indent">&#x00A0;&#x00A0;&#x00A0;&#x00A0;</named-content>Private</td><td align="left" valign="top">1018 (29.9)</td></tr><tr><td align="left" valign="top"><named-content content-type="indent">&#x00A0;&#x00A0;&#x00A0;&#x00A0;</named-content>Public</td><td align="left" valign="top">2347 (68.9)</td></tr><tr><td align="left" valign="top"><named-content content-type="indent">&#x00A0;&#x00A0;&#x00A0;&#x00A0;</named-content>Self-pay</td><td align="left" valign="top">39 (1.1)</td></tr><tr><td align="left" valign="top" colspan="2">Prescribed antibiotic</td></tr><tr><td align="left" valign="top"><named-content content-type="indent">&#x00A0;&#x00A0;&#x00A0;&#x00A0;</named-content>Amoxicillin</td><td align="left" valign="top">2757 (81.0)</td></tr><tr><td align="left" valign="top"><named-content content-type="indent">&#x00A0;&#x00A0;&#x00A0;&#x00A0;</named-content>Amoxicillin-clavulanate</td><td align="left" valign="top">544 (16.0)</td></tr><tr><td align="left" valign="top"><named-content content-type="indent">&#x00A0;&#x00A0;&#x00A0;&#x00A0;</named-content>Cefdinir</td><td align="left" valign="top">103 (3.0)</td></tr><tr><td align="left" valign="top" colspan="2">Ethnicity</td></tr><tr><td align="left" valign="top"><named-content content-type="indent">&#x00A0;&#x00A0;&#x00A0;&#x00A0;</named-content>Declined</td><td align="left" valign="top">66 (1.9)</td></tr><tr><td align="left" valign="top"><named-content content-type="indent">&#x00A0;&#x00A0;&#x00A0;&#x00A0;</named-content>Hispanic or Latino</td><td align="left" valign="top">1416 (41.6)</td></tr><tr><td align="left" valign="top"><named-content content-type="indent">&#x00A0;&#x00A0;&#x00A0;&#x00A0;</named-content>Not Hispanic or Latino</td><td align="left" valign="top">1918 (56.3)</td></tr><tr><td align="left" valign="top"><named-content content-type="indent">&#x00A0;&#x00A0;&#x00A0;&#x00A0;</named-content>Unknown</td><td align="left" valign="top">4 (0.1)</td></tr></tbody></table><table-wrap-foot><fn id="table1fn1"><p><sup>a</sup>Patients may have had more than one encounter if they presented more than once in the study period.</p></fn></table-wrap-foot></table-wrap></sec></sec><sec id="s2-2"><title>Step 2: Define Key Concepts and Data Elements</title><sec id="s2-2-1"><title>Case Study: EHR Data Retrieval Settings</title><p>For the second step, there are a few baseline definitions that will be used to describe the process of pulling this data:</p><list list-type="bullet"><list-item><p>Foreign key: a field in SQL databases used to link records across relational tables (eg, patient ID)</p></list-item><list-item><p>Triggering event: an EHR interaction (eg, an appointment, refill request, or telephone encounter) that initiates the batch retrieval of external pharmacy data</p></list-item><list-item><p>Match proportion: the percentage of orders successfully linked to a dispense record</p></list-item></list><p>In this step, it is important to define these elements and to be aware of what the triggering event settings are within your EHR. A triggering event activates the pulling of data from the external dispense data vendor for each event, and the data pull is often marked with the date when the data were retrieved. It is also important to be aware of the look-back period for the data pull.</p></sec><sec id="s2-2-2"><title>Case Study Example</title><p>At our institution, the University of California, San Francisco (UCSF), the system retrieves up to 365 days of prior dispense data at the time of a triggering event. Triggering events in our EHR include refill encounters, order encounters, hospital encounters, appointments, patient messages, or telephone encounters.</p><p>Within our system, there is no distinct foreign key that can be used to match the data to the external dispense data. The order ID for a specific medication in our system is not reflected in the commercial database. Thus, we cannot easily match an order from an encounter to a specific dispense from the pharmacy database. As a result, we had to develop surrogate key logic with multiple steps, which is outlined in Step 4.</p></sec></sec><sec id="s2-3"><title>Step 3: Data Extraction</title><sec id="s2-3-1"><title>Case Study: EHR Data Extraction</title><p>Data should be extracted from the EHR reporting database. This typically involves developing and testing a SQL query. The key step here is to identify the order data, patient information, and pharmacy and medication information. Researchers may consider including the following to augment their analysis:</p><list list-type="bullet"><list-item><p>Encounter data: clinic setting, department, date, time of appointment or encounter, time that the encounter was made, check-in time, diagnosis code, encounter note, and patient after-visit summary</p></list-item><list-item><p>Order data: order time, order date, order number, and ordering provider</p></list-item><list-item><p>Patient information: name, patient identifier, birthdate, address, sex, race, ethnicity, language, and insurance status</p></list-item><list-item><p>Pharmacy: pharmacy name, phone number, and address</p></list-item><list-item><p>Medication information: name, concentration, dose, and comments to the pharmacy</p></list-item></list><p>Next, it is important to locate the external dispense data and, if necessary, join it to the same patient, pharmacy, and medication information tables.</p></sec><sec id="s2-3-2"><title>Case Study Example</title><p>Data were extracted from Epic Clarity. The SQL queries used for data extraction were developed and internally reviewed by the study authors. The original code was written by JP and subsequently updated and revised by BM. No separate IT or external technical review of the SQL code was performed. Both authors are Epic Clarity&#x2013;certified.</p><p>The research team performed random sampling of records to verify data integrity and ensure inclusion criteria were met. We were able to identify the order, patient, medication, and pharmacy tables, along with the external dispense data tables. Due to copyright restrictions and privacy agreements governing the proprietary EHR data tables, we are unable to share the exact code used in this project. Instead, we provide a simplified, illustrative outline of the coding approach on GitHub [<xref ref-type="bibr" rid="ref16">16</xref>], and a Jupyter notebook containing deidentified practice data is also provided on GitHub [<xref ref-type="bibr" rid="ref17">17</xref>]. An archived version corresponding to this publication is available through Zenodo [<xref ref-type="bibr" rid="ref18">18</xref>]. The repository is intended to demonstrate the general analytic workflow and is not a runnable or complete implementation of the analysis; therefore, it should not be used to reproduce the analysis directly.</p><p>Our institution has a proprietary agreement with DrFirst for the majority of our database dispenses. We also maintain a relationship with Surescripts as a backup and for certain insurance types.</p></sec></sec><sec id="s2-4"><title>Step 4: Linkage Strategy</title><sec id="s2-4-1"><title>Case Study: EHR and External Dispense Data Linkage</title><p>Your EHR may not contain a foreign key that can be used to link the external dispense information to the internal order (such as an order ID). To match at the order level, this can be accomplished by leveraging surrogate secondary keys in a multilookup configuration to ensure you have the correct order. The patient, medication, and pharmacy identifiers are often present in both the ordering and the outpatient dispense tables within the database. All three should be used at a minimum. Additionally, if needed for the use case, ordering provider identifiers, such as a Drug Enforcement Administration number or a National Provider Identifier (NPI), can be leveraged. The reader should note that clinics with multiple ordering providers&#x2014;trainees, such as residents and fellows, or advanced practice providers&#x2014;may have discrepancies between the ordering provider and the attending physician who signed the visit.</p></sec><sec id="s2-4-2"><title>Case Study Example</title><p>Linking the EHR encounter to the correct outpatient dispense record was the central challenge of our project. The foreign key that our EHR vendor suggested would be associated with the order data was unusable because the order number sent by our EHR does not match the prescription number used by the pharmacy processing software. Additionally, the dispense data received did not contain the original EHR order number that we could locate.</p><p>Identification of a common key is a challenge that most EHRs face with outpatient, external prescription dispense data, as internal data primary keys rarely match those used by external pharmacies or databases. Thus, multiple matches using secondary keys must be used with conditional join logic to establish the correct link. This is in contrast to internal inpatient hospital pharmacies, which will likely share order IDs, thereby simplifying the linkage between encounters and dispenses.</p><p>For our outpatient use case, we used Generic Control Number (GCN; First DataBank [<xref ref-type="bibr" rid="ref19">19</xref>])&#x2013;based matching to group across brand/generic variations and different strengths. Pharmacy phone numbers were used as the primary link because pharmacy IDs were unstable during ownership changes, while phone numbers remained constant. Patient matching was performed upstream by the EHR and commercial pharmacy data networks using vendor-specific proprietary matching algorithms and patient identity reconciliation processes. These matching procedures, which may incorporate multiple patient identifiers and vendor-defined heuristics, were not part of the custom code developed for this study and were not accessible to the study team. The study&#x2019;s code used the EHR-assigned patient primary key to identify and filter orders associated with each patient.</p><p>Our approach was as follows: First, all antibiotic orders for AOM associated with relevant office visits and emergency department encounters were extracted, as described in step 3. Second, patient, medication, pharmacy, and provider information were joined to the order data. Third, using the outside pharmacy dispense data, the orders were joined using the internal EHR patient identifier, pharmacy phone number, or pharmacy ID. Fourth, the order medication GCN was matched to the prescription National Drug Code (NDC), and then to the GCN corresponding to that NDC. Finally, the prescription dispense date was matched to a date up to 14 days after the order date. Fourteen days was selected for our particular use case because AOM is expected to resolve within 2 weeks [<xref ref-type="bibr" rid="ref20">20</xref>], and any symptoms persisting beyond this period are typically indicative of a new infection [<xref ref-type="bibr" rid="ref21">21</xref>]. Readers may choose to change this dispense period depending on the type of behavior they expect from patients for the particular medication under study.</p><p>These joins are representative of the types of foreign keys needed to accurately join EHR order information to external prescription dispense data. We chose to use GCN, as it allowed for matches between brand and generic products. The pharmacy phone number was necessary because some pharmacies had changed ownership and the pharmacy ID in our EHR did not match the pharmacy ID in the dispense data, while the phone number remained the same.</p><p>In our logic, we did not use the prescriber name or NPI due to the heavy presence of trainees in our clinics, which means that the prescriber might not match the attending provider assigned to the encounter. Using the NPI could have been used to further restrict matching to the ordering provider in clinics that do not have such a large trainee presence. Potential joins are outlined in <xref ref-type="fig" rid="figure1">Figure 1</xref>, with details for consideration provided in <xref ref-type="table" rid="table2">Table 2</xref>.</p><p>To ensure that we had dispense data for each encounter, we limited the analysis to patients who had a dispense data triggering event at UCSF within 365 days of the initial encounter. Triggering events in our EHR were defined as follows: refill encounters, order encounters, hospital encounters, appointments, patient messages, or telephone encounters. This restriction was necessary as dispense data are retrieved from the pharmacy server only when the EHR identifies a triggering event. For scheduled appointments, this retrieval occurs via a batch job run during off-hours. This allows the data to be viewable to the outpatient clinician at the time of the appointment.</p><p>What constitutes a triggering event and the lookback period for retrieving dispense data will vary depending on an institution&#x2019;s EHR configuration. At UCSF, our configuration&#x2019;s look-back period pulled 365 days of dispense data for a triggering event. Once retrieval is initiated by a triggering event, the dispense history is extracted to the reporting server for future analysis during the standard extract, transfer, and load process for the EHR.</p><fig position="float" id="figure1"><label>Figure 1.</label><caption><p>Conceptual flow diagram illustrating how patient, prescription, and pharmacy data could be linked in an SQL database to retrieve dispense data depending on researchers&#x2019; needs.</p></caption><graphic alt-version="no" mimetype="image" position="float" xlink:type="simple" xlink:href="jmir_v28i1e90954_fig01.png"/></fig><table-wrap id="t2" position="float"><label>Table 2.</label><caption><p>Approaches for linking SQL tables to retrieve medication dispense data.</p></caption><table id="table2" frame="hsides" rules="groups"><thead><tr><td align="left" valign="bottom">Concept</td><td align="left" valign="bottom">Option</td><td align="left" valign="bottom">Considerations</td></tr></thead><tbody><tr><td align="left" valign="top">Patient</td><td align="left" valign="top">EHR<sup><xref ref-type="table-fn" rid="table2fn1">a</xref></sup> patient identifier</td><td align="left" valign="top">Received data will already be linked to the patient&#x2014;can only be used for integrated pharmacies. Users can consider birth date and full name if the patient ID is unavailable.</td></tr><tr><td align="left" valign="top">EHR order</td><td align="left" valign="top">EHR medication order ID</td><td align="left" valign="top">Can typically only be used for integrated pharmacies, as the order number will vary between in-house EHR and pharmacy databases.</td></tr><tr><td align="left" valign="top">Pharmacy</td><td align="left" valign="top">EHR pharmacy identifier, phone number, or NABP<sup><xref ref-type="table-fn" rid="table2fn2">b</xref></sup></td><td align="left" valign="top">EHR pharmacy identifier may not be included in the outside data or could have duplicates if the pharmacy has changed ownership. Including the phone number or address may also be possible.</td></tr><tr><td align="left" valign="top">Prescriber</td><td align="left" valign="top">NPI<sup><xref ref-type="table-fn" rid="table2fn3">c</xref></sup> and DEA<sup><xref ref-type="table-fn" rid="table2fn4">d</xref></sup></td><td align="left" valign="top">Prescriber Name and NPI can be used to tie back to original order. Users should note that medication adjustments sometimes result in a change in the prescriber information sent back by the pharmacy. This is a strong consideration in trainee clinics, where attendings may change orders sent by residents.</td></tr><tr><td align="left" valign="top">Medication</td><td align="left" valign="top">EHR medication ID, generic identifier, generic name</td><td align="left" valign="top">EHR medication ID can exclude brand-generic matches. GCN<sup><xref ref-type="table-fn" rid="table2fn5">e</xref></sup> or GPI<sup><xref ref-type="table-fn" rid="table2fn6">f</xref></sup> are examples of generic identifiers that can be used. Additionally, matches across strengths are needed using the generic name will allow for this match.</td></tr></tbody></table><table-wrap-foot><fn id="table2fn1"><p><sup>a</sup>EHR: electronic health record.</p></fn><fn id="table2fn2"><p><sup>b</sup>NABP: National Association of Boards of Pharmacy.</p></fn><fn id="table2fn3"><p><sup>c</sup>NPI: National Provider Identifier.</p></fn><fn id="table2fn4"><p><sup>d</sup>DEA: Drug Enforcement Administration.</p></fn><fn id="table2fn5"><p><sup>e</sup>GCN: Generic Control Number.</p></fn><fn id="table2fn6"><p><sup>f</sup>GPI: Generic Product Identifier.</p></fn></table-wrap-foot></table-wrap></sec></sec><sec id="s2-5"><title>Step 5: Deduplication Across Data Sources</title><sec id="s2-5-1"><title>Case Study: Deduplication of Pharmacy Dispense Data</title><p>When dispense data are aggregated from multiple vendors, duplicate records must be identified and merged to avoid overcounting fulfillment. Multiple triggering events may pull the same medication dispense record. For example, consider a medication order for amoxicillin that is sent from an emergency department on a Monday and dispensed at an outpatient pharmacy later that same day. If you were to check the EHR that evening, you would not see the dispense because the patient would not yet have had a triggering event to bring that dispense from the pharmacy database into the institutional EHR. Imagine that later that same week, on Tuesday, the patient visits their physician for a different medication refill. At that Tuesday visit, the dispense from Monday would be evident because, in anticipation of the Tuesday appointment, the extract, transfer, and load would have run the night prior, retrieved the pharmacy database information, and incorporated it into the EHR.</p><p>However, most studies do not focus on such recent prescriptions but instead analyze long retrospective time periods. Going back to the example, imagine the patient then sees another provider on Thursday. If each of those encounters is a triggering event, the same dispense information would be retrieved on Tuesday and again on Thursday, leading to duplicate rows in the EHR.</p><p>This deduplication challenge arises because each triggering event returns the same underlying dispense record. In this example, the dispense that occurred on Monday, with triggering events on Tuesday and Thursday, would produce rows with identical dispense date, medication identifier, pharmacy identifier, and patient identifier. Without deduplication, these would appear as multiple dispenses. The researcher conducting a retrospective study must, therefore, distinguish data retrieved across multiple triggering events that may represent the same underlying dispense. Failing to do so could lead to grossly overestimating the number of dispenses, misrepresenting the true time of the dispense, or associating the wrong dispense with the encounter. In this example, it could appear that the patient received the prescription multiple times rather than once.</p><p>To address this, medication dispense data should be deduplicated by grouping key fields such as patient, dispense date, pharmacy, provider, and medication. This grouping produces a single record per dispense, regardless of whether the source data originated from a prescription-processing system or a payer claim.</p><p>Finally, your EHR may integrate data from multiple third-party dispense vendors. Depending on system configuration, one or more vendors may be queried per triggering event. The same grouping logic ensures a single-row representation even when multiple vendor sources contribute overlapping data.</p></sec><sec id="s2-5-2"><title>Case Study Example</title><p>Of the 2 commercial pharmacy databases integrated into the EHR system, DrFirst provided the majority of the data, with 2345 (68.9%) exclusive entries, while SureScripts contributed 57 (1.7%) entries. Only 214 (6.3%) orders had dispense data available from both databases (<xref ref-type="table" rid="table3">Table 3</xref>).</p><p>This distribution is consistent with DrFirst serving as the preferred vendor within our system. Instances of overlap likely arise from multiple triggering events for a given prescription or from differences in data availability over time.</p><p>For example, dispense data may have been unavailable from DrFirst at an initial triggering event and was therefore pulled from Surescripts, but subsequently became available at a later event, resulting in retrieval from both sources across consecutive time points. In these instances, records were merged using the above deduplication grouping into a single &#x201C;Dispensed&#x201D; status to ensure that the match proportion was not artificially inflated.</p><table-wrap id="t3" position="float"><label>Table 3.</label><caption><p>Commercial pharmacy database source (N=3404).</p></caption><table id="table3" frame="hsides" rules="groups"><thead><tr><td align="left" valign="bottom">Database</td><td align="left" valign="bottom">n<sup><xref ref-type="table-fn" rid="table3fn1">a</xref></sup> (%)</td></tr></thead><tbody><tr><td align="left" valign="top">DrFirst only</td><td align="left" valign="top">2345 (68.9)</td></tr><tr><td align="left" valign="top">No dispense data</td><td align="left" valign="top">788 (23.1)</td></tr><tr><td align="left" valign="top">Both</td><td align="left" valign="top">214 (6.3)</td></tr><tr><td align="left" valign="top">Surescripts only</td><td align="left" valign="top">57 (1.7)</td></tr></tbody></table><table-wrap-foot><fn id="table3fn1"><p><sup>a</sup>Percentages are calculated from the total N and may not sum to 100% due to rounding.</p></fn></table-wrap-foot></table-wrap></sec></sec><sec id="s2-6"><title>Step 6: Pharmacy Normalization</title><sec id="s2-6-1"><title>Case Study: Pharmacy Identifier Normalization</title><p>Pharmacy identifiers must be harmonized to account for discrepancies between the EHR&#x2019;s &#x201C;intended&#x201D; sent to pharmacy and the &#x201C;actual&#x201D; dispensing pharmacy. Pharmacy addresses, phone numbers, National Association of Boards of Pharmacy (NABP) numbers, or NPI numbers can be used to match the dispense data to the order data. The pharmacy phone number and address often remain unchanged when a pharmacy changes ownership, whereas the NPI or NABP numbers are sometimes updated.</p><p>Additionally, it is helpful to categorize your pharmacy data into large groups based on the company. This becomes important during the validation step to determine whether pharmacies are sending dispense data to the database.</p></sec><sec id="s2-6-2"><title>Case Study Example</title><p>We categorized 307 pharmacies into the following groups: CVS, Walgreens, Safeway, Rite Aid, Walmart, Costco, On-Site Hospital Pharmacy, Other, and Kaiser. Normalization revealed significant variation in data capture: large chains such as Walgreens and CVS showed an 82.4% and 81.9% match proportion, respectively, while &#x201C;Other&#x201D; pharmacies dropped to 49.3%, and Kaiser/Costco showed the lowest retrieval proportion (<xref ref-type="table" rid="table4">Table 4</xref>).</p><table-wrap id="t4" position="float"><label>Table 4.</label><caption><p>Pharmacy locations, number of prescriptions sent, and number of prescriptions with recorded dispense data from our single academic institution<sup><xref ref-type="table-fn" rid="table4fn1">a</xref></sup>.</p></caption><table id="table4" frame="hsides" rules="groups"><thead><tr><td align="left" valign="bottom">Pharmacy (n=307 locations)</td><td align="left" valign="bottom">Number of prescriptions sent (percentage of all prescriptions sent), n (%)<sup><xref ref-type="table-fn" rid="table4fn2">b</xref></sup></td><td align="left" valign="bottom">Prescriptions dispensed (percent dispensed within this pharmacy chain), n (%)<sup><xref ref-type="table-fn" rid="table4fn2">b</xref></sup></td></tr></thead><tbody><tr><td align="left" valign="top">Walgreens (n=114)</td><td align="left" valign="top">1579 (46.4)</td><td align="left" valign="top">1301 (82.4)</td></tr><tr><td align="left" valign="top">On-site pharmacy (n=2)</td><td align="left" valign="top">994 (29.2)</td><td align="left" valign="top">671 (67.5)</td></tr><tr><td align="left" valign="top">CVS (n=96)</td><td align="left" valign="top">547 (16.1)</td><td align="left" valign="top">448 (81.9)</td></tr><tr><td align="left" valign="top">Safeway (n=29)</td><td align="left" valign="top">110 (3.2)</td><td align="left" valign="top">80 (72.7)</td></tr><tr><td align="left" valign="top">Other (n=30)</td><td align="left" valign="top">71 (2.1)</td><td align="left" valign="top">35 (49.3)</td></tr><tr><td align="left" valign="top">Rite Aid (n=16)</td><td align="left" valign="top">58 (1.7)</td><td align="left" valign="top">51 (87.9)</td></tr><tr><td align="left" valign="top">Walmart (n=10)</td><td align="left" valign="top">31 (0.9)</td><td align="left" valign="top">27 (87.1)</td></tr><tr><td align="left" valign="top">Costco (n=6)</td><td align="left" valign="top">9 (0.3)</td><td align="left" valign="top">2 (22.2)</td></tr><tr><td align="left" valign="top">Kaiser (n=4)</td><td align="left" valign="top">5 (0.1)</td><td align="left" valign="top">1 (20.0)</td></tr><tr><td align="left" valign="top">Total</td><td align="left" valign="top">3404 (100)</td><td align="left" valign="top">2616 (76.9)</td></tr></tbody></table><table-wrap-foot><fn id="table4fn1"><p><sup>a</sup>&#x201C;Number of prescriptions sent&#x201D; represents the number and proportion of prescriptions in the study cohort sent to each pharmacy. &#x201C;Prescriptions dispensed&#x201D; represents the absolute number of prescriptions that were dispensed and the respective proportion of prescriptions sent to that pharmacy that were ultimately recorded as dispensed in the EHR. These data are reported per encounter, not per patient; patients may have contributed multiple encounters during the study period.</p></fn><fn id="table4fn2"><p><sup>b</sup>Percentages in the n (%) column are calculated from the total N and may not sum to 100% due to rounding.</p></fn></table-wrap-foot></table-wrap></sec></sec><sec id="s2-7"><title>Step 7: Validation and Quality Assurance</title><sec id="s2-7-1"><title>Case Study: Linkage Validation and Pharmacy Reporting</title><p>Validation of the joins and pharmacy inclusion in the dispense data source is essential. First, evaluate the matched order-to-prescription data for a subset of your total data to validate that it is correctly using the logic to match the order to the dispense or claim. Second, gather the distinct pharmacies included in your order dataset and evaluate whether dispense data have been received for any patients. We also recommend comparing characteristics of linked vs unlinked orders (eg, patient demographics, encounter type, or pharmacy type) to assess potential bias in linkage.</p><p>To further ensure completeness of pharmacy reporting, we extracted the full list of pharmacies present in our order dataset and queried our EHR reporting database (Clarity) to determine whether each pharmacy had returned any dispense records for any medication and any patient during the study period. This step was used to confirm that pharmacies included in the analysis were actively transmitting data through the commercial pharmacy aggregation system into the EHR, rather than appearing not to have dispenses that were attributable to linkage or data availability issues. Specifically, we recommend pulling the first dispense date, last dispense date, and total number of dispenses for each pharmacy. This step confirms whether a pharmacy is a &#x201C;reporting&#x201D; pharmacy.</p><p>It is important to keep in mind that patients without a follow-up triggering event will not have any dispense data&#x2014;which is why it is important to ensure that all included pharmacies are reporting. Generally, patients without a follow-up triggering event should be excluded from the analysis, as they will never have corresponding dispense data.</p><p>As an additional validation step, a subset of linkages could be reviewed to confirm concordance between ordered medications and dispensed products (eg, agreement with NDC). More comprehensive validation of linkage accuracy and data completeness&#x2014;such as quantifying potential data transmission loss between the EHR and PDS&#x2014;would require access to both systems. Such analyses were beyond the scope of this study but represent an important area for future work.</p></sec><sec id="s2-7-2"><title>Case Study Example</title><p>Overall, 307 pharmacies were included in our cohort. Of these, 302 (98.3%) were confirmed to have returned at least 1 dispense record for any medication and for any patient in the EHR during the study period, indicating active data transmission. Within our study cohort, most patients elected to send their medications to large pharmacy chains such as CVS and Walgreens, whereas 994 (29.2%) prescriptions were sent to the local hospital pharmacy (<xref ref-type="table" rid="table4">Table 4</xref>). Only 71 (2.1%) encounters involved a pharmacy that was neither a major chain nor the local hospital pharmacy.</p><p>Of the 3404 antibiotic orders, 2616 (76.9%) were successfully linked to dispense data using the multikey strategy. Depending on which keys are used, this number will likely fluctuate. Linkage performance should also be evaluated under different combinations of available data elements, as missing or inconsistently captured fields may reduce the match proportion. To assess linkage validity, a subset of matched records was manually reviewed to confirm concordance between the physician notes, ordered medications, and dispensed products (eg, agreement between medication identity and the NDC).</p><p>In our dataset, on-site pharmacies demonstrated a lower observed dispense percentage. This likely reflects temporal operational factors during the study period, including a transition from a third-party vendor (Walgreens) to an internally managed UCSF pharmacy system, as well as concurrent contractual and data integration changes. These disruptions may have affected the capture and availability of dispense data in the EHR, leading to under-ascertainment of dispenses rather than true differences in patient medication pickup behavior.</p></sec></sec></sec><sec id="s3" sec-type="discussion"><title>Discussion</title><sec id="s3-1"><title>Principal Findings</title><p>This study demonstrates a methodology for using commercial pharmacy databases integrated into the EHR to assess medication adherence patterns, offering an alternative to traditional claims data. We obtained dispense data for 76.9% of orders for AOM. Given that more than 98.3% of pharmacies in our cohort have historically reported dispense data to our EHR, it is likely that the remaining 23.1% of orders were truly not dispensed rather than representing missing data.</p><p>The dispense proportion for antibiotics is consistent with prior reports for pediatric prescription dispense proportions&#x2014;approximately 80% for pediatric pneumonia antibiotics [<xref ref-type="bibr" rid="ref22">22</xref>] and 84% for pediatric antibiotics overall [<xref ref-type="bibr" rid="ref23">23</xref>]&#x2014;and is slightly higher than the 65% dispense proportion reported following emergency department visits [<xref ref-type="bibr" rid="ref24">24</xref>]. It is important to note, however, that these figures reflect prescription dispensing rather than actual medication use; adherence to actually taking antibiotics is estimated to be closer to 62% [<xref ref-type="bibr" rid="ref25">25</xref>]. In our cohort, DrFirst captured the majority of dispensed orders (n=2345, 68.9%), reflective of institutional agreement with it as our primary dispense source.</p></sec><sec id="s3-2"><title>Evaluating Data Key Logic</title><p>The choice of foreign keys for linking medications warrants careful consideration, as the selected medication identifier directly affects the logic used to match EHR orders to dispense records. <xref ref-type="table" rid="table2">Table 2</xref> provides examples of the join granularity when different keys are used. <xref ref-type="fig" rid="figure1">Figure 1</xref> illustrates example matches between data tables. Depending on the research question, some or all of these data elements can serve as keys, and the selection should align with the desired level of match. In addition to medication-specific keys, the other keys listed in the table represent options that can be leveraged depending on what is available in the dispense data at a given institution. For example, if patient ID is not present in the dispense history, secondary keys like patient name and date of birth may need to be used.</p><p>Using the provider as a matching key can be advantageous when the goal is to link dispenses to a specific prescriber. However, we did not use this approach in our study due to the complexity introduced by trainees such as residents and fellows. In these cases, a trainee may submit an order electronically, but if the pharmacy later calls to clarify formulation, quantity, or strength, the provider who responds may be different from the original order. The new prescription from the pharmacy will list the provider who answered the phone, which may differ from the encounter record. This issue is likely less problematic in settings without trainees and could be valuable when assessing dispense proportions at the provider level or when examining differences by specialty. Additionally, as our study restricted the date range for the dispenses, the chance of an additional outside prescriber writing the same medication in the dispense window was minimal.</p><p>We suggest that users consider the inclusion of the generic name or generic name ID, as it allows for the identification of generic substitutions and formulation changes, which are common in pediatric prescribing practices. For example, children may be prescribed a liquid but may arrive at the pharmacy, and their parents may request a pill if they have learned how to swallow them, or vice versa. They may need adjustments to the strength or formulation of amoxicillin-clavulanate depending on what the pharmacy has in stock. For any study that uses liquid medications or involves pediatric populations, we recommend keeping this generic identifier. This flexibility in prescribing may be less relevant in certain adult specialties, where medications may only be available in a single formulation.</p><p>While not the focus of this particular paper, it is worth mentioning that for institutions that connect to third-party vendors, these dispense data are often readily available to users, which allows clinicians to use these data in clinical practice. In the ambulatory setting, these data may be available under a medication history dispense tab and help providers identify the most recent antibiotic prescriptions or determine whether patients are picking up medications for a chronic condition, such as asthma inhalers or antidepressants. By integrating these data into routine workflows, clinicians can make more informed decisions about patient care, address potential barriers to adherence, tailor education during the visit, and then use the above-detailed methodology for large-scale epidemiological research. Excitingly, these data also have the potential to be used for clinical decision support tools, for example, by alerting clinicians when a patient appears to be nonadherent to their prescribed medications, enabling timely intervention [<xref ref-type="bibr" rid="ref26">26</xref>].</p></sec><sec id="s3-3"><title>Limitations</title><p>The major challenge of this project was the lack of a distinct foreign key to directly link EHR prescribing data with pharmacy dispensing data. This limitation necessitated the use of multiple joins and matching variables, which may have introduced some degree of error into the dataset. While the matching process was carefully designed to minimize inaccuracies, the absence of a definitive linking mechanism remains a potential source of error. Readers should be especially cognizant of this step when recreating this tutorial for their own datasets.</p><p>Understanding which pharmacies are predominantly used by the patient population is critical when designing studies that rely on this type of data. Although this limitation was less relevant for our geographically concentrated pediatric population in the San Francisco Bay Area&#x2014;where 98.3% of pharmacies reported data to the health information exchange&#x2014;it remains an important consideration for other settings. Investigators should confirm that the dispense data in their EHRs adequately capture the population of interest to ensure the validity of their findings.</p><p>Restricting the cohort to patients who returned to UCSF within 365 days was necessary to enable querying of the pharmacy database server. While this approach ensured that dispense data would be captured when available, it introduced selection bias by excluding patients without follow-up, who may differ systematically in care access or utilization. This is a key limitation of the underlying data and technology. As a result, the method is less applicable to patients with only a single point of care, such as those seen in the emergency department. The approach is therefore most useful as a QI tool for patients with ongoing care at the site, whether through a primary care provider or a specialty clinic managing chronic conditions, such as rheumatology.</p><p>We limited the dataset to 14 days, which may have excluded additional dispenses that occurred later. For our purposes&#x2014;focusing on an acute infection&#x2014;a short timeframe was necessary. For studies of chronic conditions, where timing is less critical, this window could be extended to capture a more comprehensive medication use.</p><p>It is also important to note that, like claims data, dispense data do not equate to medication use. While the study successfully identified whether prescriptions were dispensed, it could not confirm whether patients adhered to the prescribed regimen or completed the course of antibiotics.</p></sec><sec id="s3-4"><title>Conclusions</title><p>Leveraging external pharmacy prescription dispense data integrated into the EHR offers a practical, timely method to study prescription dispense behavior at scale. Our experience linking pediatric AOM prescriptions to pharmacy databases demonstrates a dispense proportion of 76.9%, providing granular insights into antibiotic and pharmacy use. Although limitations remain&#x2014;such as the absence of a definitive linking key and the need for patients to revisit the health care system&#x2014;this tutorial underscores how SQL queries and careful matching processes can build a robust dataset. The approach is readily adaptable for diverse clinical applications, from acute infections to chronic conditions, and allows providers and researchers to more accurately gauge adherence during QI efforts.</p></sec></sec></body><back><ack><p>Generative AI (ChatGPT 5.0, OpenAI, 2024, as well as Versa, a proprietary University of California, San Francisco [UCSF] HIPAA [Health Insurance Portability and Accountability Act]&#x2013;compliant instance of GPT 5.0) was used in the preparation of this manuscript to assist with word choice, sentence structure, and smoothing transitions between paragraphs based on the authors&#x2019; own first draft. All output was carefully reviewed and edited by the authors. No original scientific content, data, or claims were produced by the model.</p></ack><notes><sec><title>Funding</title><p>The authors declared no financial support was received for this work.</p></sec><sec><title>Data Availability</title><p>Due to copyright restrictions and privacy agreements governing the proprietary electronic health record data tables, we are unable to share the exact code used in this project. Instead, we provide a simplified, illustrative outline of the coding approach on GitHub [<xref ref-type="bibr" rid="ref16">16</xref>], and a Jupyter notebook containing deidentified practice data is also provided on GitHub [<xref ref-type="bibr" rid="ref17">17</xref>]. An archived version corresponding to this publication is available through Zenodo [<xref ref-type="bibr" rid="ref18">18</xref>]. The repository is intended to demonstrate the general analytic workflow and is not a runnable or complete implementation of the analysis; therefore, it should not be used to reproduce the analysis directly.</p><p>We hope these resources allow readers to understand and replicate the analytic framework.</p></sec></notes><fn-group><fn fn-type="con"><p>Conceptualization: JP, BM (equal)</p><p>Data curation: JP, BM (equal)</p><p>Formal analysis: BM (lead), JP (supporting)</p><p>Investigation: JP, BM (equal)</p><p>Methodology: JP, BM (equal)</p><p>Project administration: JP (lead)</p><p>Software: BM (lead), JP (supporting)</p><p>Validation: BM (lead), JP (supporting)</p><p>Visualization: BM (lead)</p><p>Writing &#x2013; original draft: JP (lead), BM (supporting)</p><p>Writing &#x2013; review &#x0026; editing: BM (lead), JP (supporting)</p></fn><fn fn-type="conflict"><p>None declared.</p></fn></fn-group><glossary><title>Abbreviations</title><def-list><def-item><term id="abb1">AOM</term><def><p>acute otitis media</p></def></def-item><def-item><term id="abb2">EHR</term><def><p>electronic health record</p></def></def-item><def-item><term id="abb3">GCN</term><def><p>Generic Control Number</p></def></def-item><def-item><term id="abb4">GPI</term><def><p>Generic Product Identifier</p></def></def-item><def-item><term id="abb5">ICD</term><def><p>International Classification of Diseases</p></def></def-item><def-item><term id="abb6">NABP</term><def><p>National Association of Boards of Pharmacy</p></def></def-item><def-item><term id="abb7">NDC</term><def><p>National Drug Code</p></def></def-item><def-item><term id="abb8">NPI</term><def><p>National Provider Identifier</p></def></def-item><def-item><term id="abb9">QI</term><def><p>quality improvement</p></def></def-item><def-item><term id="abb10">SNAP</term><def><p>safety net antibiotic prescription</p></def></def-item><def-item><term id="abb11">UCSF</term><def><p>University of California, San Francisco</p></def></def-item></def-list></glossary><ref-list><title>References</title><ref id="ref1"><label>1</label><nlm-citation citation-type="journal"><person-group person-group-type="author"><name name-style="western"><surname>Stirratt</surname><given-names>MJ</given-names> </name><name name-style="western"><surname>Dunbar-Jacob</surname><given-names>J</given-names> </name><name name-style="western"><surname>Crane</surname><given-names>HM</given-names> </name><etal/></person-group><article-title>Self-report measures of medication adherence behavior: recommendations on optimal use</article-title><source>Transl Behav Med</source><year>2015</year><month>12</month><volume>5</volume><issue>4</issue><fpage>470</fpage><lpage>482</lpage><pub-id pub-id-type="doi">10.1007/s13142-015-0315-2</pub-id><pub-id pub-id-type="medline">26622919</pub-id></nlm-citation></ref><ref id="ref2"><label>2</label><nlm-citation citation-type="journal"><person-group person-group-type="author"><name name-style="western"><surname>Prieto-Merino</surname><given-names>D</given-names> </name><name name-style="western"><surname>Mulick</surname><given-names>A</given-names> </name><name name-style="western"><surname>Armstrong</surname><given-names>C</given-names> </name><etal/></person-group><article-title>Estimating proportion of days covered (PDC) using real-world online medicine suppliers&#x2019; datasets</article-title><source>J Pharm Policy Pract</source><year>2021</year><month>12</month><day>29</day><volume>14</volume><issue>1</issue><fpage>113</fpage><pub-id pub-id-type="doi">10.1186/s40545-021-00385-w</pub-id><pub-id pub-id-type="medline">34965882</pub-id></nlm-citation></ref><ref id="ref3"><label>3</label><nlm-citation citation-type="web"><article-title>Measures &#x0026; resources</article-title><source>Pharmacy Quality Alliance (PQA)</source><access-date>2025-12-22</access-date><comment><ext-link ext-link-type="uri" xlink:href="https://www.pqaalliance.org/adherence-measures">https://www.pqaalliance.org/adherence-measures</ext-link></comment></nlm-citation></ref><ref id="ref4"><label>4</label><nlm-citation citation-type="journal"><person-group person-group-type="author"><name name-style="western"><surname>Haff</surname><given-names>N</given-names> </name><name name-style="western"><surname>Choudhry</surname><given-names>NK</given-names> </name><name name-style="western"><surname>Isaac</surname><given-names>T</given-names> </name><etal/></person-group><article-title>Disagreement between pharmacy claims and direct interview to identify patients with non-adherence to chronic cardiometabolic medications</article-title><source>Am Heart J</source><year>2023</year><month>02</month><volume>256</volume><fpage>51</fpage><lpage>59</lpage><pub-id pub-id-type="doi">10.1016/j.ahj.2022.10.083</pub-id><pub-id pub-id-type="medline">36780373</pub-id></nlm-citation></ref><ref id="ref5"><label>5</label><nlm-citation citation-type="journal"><person-group person-group-type="author"><name name-style="western"><surname>Blecker</surname><given-names>S</given-names> </name><name name-style="western"><surname>Adhikari</surname><given-names>S</given-names> </name><name name-style="western"><surname>Zhang</surname><given-names>H</given-names> </name><etal/></person-group><article-title>Validation of EHR medication fill data obtained through electronic linkage with pharmacies</article-title><source>J Manag Care Spec Pharm</source><year>2021</year><month>10</month><volume>27</volume><issue>10</issue><fpage>1482</fpage><lpage>1487</lpage><pub-id pub-id-type="doi">10.18553/jmcp.2021.27.10.1482</pub-id><pub-id pub-id-type="medline">34595945</pub-id></nlm-citation></ref><ref id="ref6"><label>6</label><nlm-citation citation-type="web"><source>DrFirst</source><access-date>2026-04-26</access-date><comment><ext-link ext-link-type="uri" xlink:href="https://drfirst.com/">https://drfirst.com/</ext-link></comment></nlm-citation></ref><ref id="ref7"><label>7</label><nlm-citation citation-type="web"><source>Surescripts</source><access-date>2026-04-27</access-date><comment><ext-link ext-link-type="uri" xlink:href="https://surescripts.com/">https://surescripts.com/</ext-link></comment></nlm-citation></ref><ref id="ref8"><label>8</label><nlm-citation citation-type="journal"><person-group person-group-type="author"><name name-style="western"><surname>Wu</surname><given-names>P</given-names> </name><name name-style="western"><surname>Hurst</surname><given-names>JH</given-names> </name><name name-style="western"><surname>French</surname><given-names>A</given-names> </name><name name-style="western"><surname>Chrestensen</surname><given-names>M</given-names> </name><name name-style="western"><surname>Goldstein</surname><given-names>BA</given-names> </name></person-group><article-title>Linking electronic health record prescribing data and pharmacy dispensing records to identify patient-level factors associated with psychotropic medication receipt: retrospective study</article-title><source>JMIR Med Inform</source><year>2025</year><month>03</month><day>4</day><volume>13</volume><fpage>e63740</fpage><pub-id pub-id-type="doi">10.2196/63740</pub-id><pub-id pub-id-type="medline">40035724</pub-id></nlm-citation></ref><ref id="ref9"><label>9</label><nlm-citation citation-type="journal"><person-group person-group-type="author"><name name-style="western"><surname>Blecker</surname><given-names>S</given-names> </name><name name-style="western"><surname>Zhao</surname><given-names>Y</given-names> </name><name name-style="western"><surname>Li</surname><given-names>X</given-names> </name><etal/></person-group><article-title>Approach to estimating adherence to heart failure medications using linked electronic health record and pharmacy data</article-title><source>J Gen Intern Med</source><year>2025</year><month>03</month><volume>40</volume><issue>4</issue><fpage>811</fpage><lpage>817</lpage><pub-id pub-id-type="doi">10.1007/s11606-024-09216-5</pub-id><pub-id pub-id-type="medline">39585579</pub-id></nlm-citation></ref><ref id="ref10"><label>10</label><nlm-citation citation-type="journal"><person-group person-group-type="author"><name name-style="western"><surname>Comer</surname><given-names>D</given-names> </name><name name-style="western"><surname>Couto</surname><given-names>J</given-names> </name><name name-style="western"><surname>Aguiar</surname><given-names>R</given-names> </name><name name-style="western"><surname>Wu</surname><given-names>P</given-names> </name><name name-style="western"><surname>Elliott</surname><given-names>D</given-names> </name></person-group><article-title>Using aggregated pharmacy claims to identify primary nonadherence</article-title><source>Am J Manag Care</source><year>2015</year><month>12</month><day>1</day><volume>21</volume><issue>12</issue><fpage>e655</fpage><lpage>e660</lpage><pub-id pub-id-type="medline">26760428</pub-id></nlm-citation></ref><ref id="ref11"><label>11</label><nlm-citation citation-type="journal"><person-group person-group-type="author"><name name-style="western"><surname>Jansen</surname><given-names>GP</given-names> </name><name name-style="western"><surname>Vazquez-Benitez</surname><given-names>G</given-names> </name><name name-style="western"><surname>Ehresmann</surname><given-names>K</given-names> </name><name name-style="western"><surname>Seburg</surname><given-names>EM</given-names> </name><name name-style="western"><surname>Nolan</surname><given-names>MB</given-names> </name><name name-style="western"><surname>Palmsten</surname><given-names>K</given-names> </name></person-group><article-title>Comparison of linked EHR-pharmacy data and administrative claims data: medication fills during pregnancy</article-title><source>Pharmacoepidemiol Drug Saf</source><year>2025</year><month>12</month><volume>34</volume><issue>12</issue><fpage>e70271</fpage><pub-id pub-id-type="doi">10.1002/pds.70271</pub-id><pub-id pub-id-type="medline">41285557</pub-id></nlm-citation></ref><ref id="ref12"><label>12</label><nlm-citation citation-type="journal"><person-group person-group-type="author"><name name-style="western"><surname>Pourian</surname><given-names>JJ</given-names> </name><name name-style="western"><surname>Michaels</surname><given-names>B</given-names> </name><name name-style="western"><surname>Vo</surname><given-names>A</given-names> </name><name name-style="western"><surname>Holmgren</surname><given-names>AJ</given-names> </name><name name-style="western"><surname>Garcia-Agundez</surname><given-names>A</given-names> </name><name name-style="western"><surname>Flaherman</surname><given-names>V</given-names> </name></person-group><article-title>A SNAPpy use of large language models: using large language models to classify treatment plans in pediatric acute otitis media</article-title><source>J Am Med Inform Assoc</source><year>2025</year><month>12</month><day>1</day><volume>32</volume><issue>12</issue><fpage>1947</fpage><lpage>1951</lpage><pub-id pub-id-type="doi">10.1093/jamia/ocaf170</pub-id><pub-id pub-id-type="medline">41069025</pub-id></nlm-citation></ref><ref id="ref13"><label>13</label><nlm-citation citation-type="journal"><person-group person-group-type="author"><name name-style="western"><surname>Pourian</surname><given-names>J</given-names> </name><name name-style="western"><surname>Michaels</surname><given-names>B</given-names> </name><name name-style="western"><surname>Vo</surname><given-names>A</given-names> </name><name name-style="western"><surname>Holmgren</surname><given-names>AJ</given-names> </name><name name-style="western"><surname>Garcia-Agundez</surname><given-names>A</given-names> </name><name name-style="western"><surname>Flaherman</surname><given-names>V</given-names> </name></person-group><article-title>Characterising 'watch and wait' prescribing patterns in paediatric otitis media using large language models and pharmacy dispense data</article-title><source>BMJ Health Care Inform</source><year>2026</year><month>06</month><day>22</day><volume>33</volume><issue>1</issue><fpage>e101948</fpage><pub-id pub-id-type="doi">10.1136/bmjhci-2025-101948</pub-id><pub-id pub-id-type="medline">42331507</pub-id></nlm-citation></ref><ref id="ref14"><label>14</label><nlm-citation citation-type="journal"><person-group person-group-type="author"><name name-style="western"><surname>Vojtek</surname><given-names>I</given-names> </name><name name-style="western"><surname>Nordgren</surname><given-names>M</given-names> </name><name name-style="western"><surname>Hoet</surname><given-names>B</given-names> </name></person-group><article-title>Impact of pneumococcal conjugate vaccines on otitis media: a review of measurement and interpretation challenges</article-title><source>Int J Pediatr Otorhinolaryngol</source><year>2017</year><month>09</month><volume>100</volume><fpage>174</fpage><lpage>182</lpage><pub-id pub-id-type="doi">10.1016/j.ijporl.2017.07.009</pub-id><pub-id pub-id-type="medline">28802367</pub-id></nlm-citation></ref><ref id="ref15"><label>15</label><nlm-citation citation-type="journal"><person-group person-group-type="author"><name name-style="western"><surname>Hu</surname><given-names>T</given-names> </name><name name-style="western"><surname>Done</surname><given-names>N</given-names> </name><name name-style="western"><surname>Petigara</surname><given-names>T</given-names> </name><etal/></person-group><article-title>Incidence of acute otitis media in children in the United States before and after the introduction of 7- and 13-valent pneumococcal conjugate vaccines during 1998-2018</article-title><source>BMC Infect Dis</source><year>2022</year><month>03</month><day>26</day><volume>22</volume><issue>1</issue><fpage>294</fpage><pub-id pub-id-type="doi">10.1186/s12879-022-07275-9</pub-id><pub-id pub-id-type="medline">35346092</pub-id></nlm-citation></ref><ref id="ref16"><label>16</label><nlm-citation citation-type="web"><article-title>Beenjamming/dispensedataehrorders</article-title><source>GitHub</source><access-date>2026-09-22</access-date><comment><ext-link ext-link-type="uri" xlink:href="https://github.com/Beenjamming/DispenseDataEHROrders">https://github.com/Beenjamming/DispenseDataEHROrders</ext-link></comment></nlm-citation></ref><ref id="ref17"><label>17</label><nlm-citation citation-type="web"><article-title>SampleMedicationDataLoad.ipynb</article-title><source>GitHub</source><access-date>2026-09-22</access-date><comment><ext-link ext-link-type="uri" xlink:href="https://github.com/Beenjamming/DispenseDataEHROrders/blob/main/SampleMedicationDataLoad.ipynb">https://github.com/Beenjamming/DispenseDataEHROrders/blob/main/SampleMedicationDataLoad.ipynb</ext-link></comment></nlm-citation></ref><ref id="ref18"><label>18</label><nlm-citation citation-type="web"><article-title>Beenjamming/DispenseDataEHROrders: Dispense Data EHR Orders</article-title><source>Zenodo</source><access-date>2026-09-22</access-date><comment><ext-link ext-link-type="uri" xlink:href="https://zenodo.org/records/22259685">https://zenodo.org/records/22259685</ext-link></comment></nlm-citation></ref><ref id="ref19"><label>19</label><nlm-citation citation-type="web"><source>FDB (First Databank)</source><access-date>2026-04-26</access-date><comment><ext-link ext-link-type="uri" xlink:href="https://www.fdbhealth.com/">https://www.fdbhealth.com/</ext-link></comment></nlm-citation></ref><ref id="ref20"><label>20</label><nlm-citation citation-type="journal"><person-group person-group-type="author"><name name-style="western"><surname>Le Saux</surname><given-names>N</given-names> </name><name name-style="western"><surname>Gaboury</surname><given-names>I</given-names> </name><name name-style="western"><surname>Baird</surname><given-names>M</given-names> </name><etal/></person-group><article-title>A randomized, double-blind, placebo-controlled noninferiority trial of amoxicillin for clinically diagnosed acute otitis media in children 6 months to 5 years of age</article-title><source>CMAJ</source><year>2005</year><month>02</month><day>1</day><volume>172</volume><issue>3</issue><fpage>335</fpage><lpage>341</lpage><pub-id pub-id-type="doi">10.1503/cmaj.1040771</pub-id><pub-id pub-id-type="medline">15684116</pub-id></nlm-citation></ref><ref id="ref21"><label>21</label><nlm-citation citation-type="journal"><person-group person-group-type="author"><name name-style="western"><surname>Leibovitz</surname><given-names>E</given-names> </name><name name-style="western"><surname>Greenberg</surname><given-names>D</given-names> </name><name name-style="western"><surname>Piglansky</surname><given-names>L</given-names> </name><etal/></person-group><article-title>Recurrent acute otitis media occurring within one month from completion of antibiotic therapy: relationship to the original pathogen</article-title><source>Pediatr Infect Dis J</source><year>2003</year><month>03</month><volume>22</volume><issue>3</issue><fpage>209</fpage><lpage>216</lpage><pub-id pub-id-type="doi">10.1097/01.inf.0000066798.69778.07</pub-id><pub-id pub-id-type="medline">12634580</pub-id></nlm-citation></ref><ref id="ref22"><label>22</label><nlm-citation citation-type="journal"><person-group person-group-type="author"><name name-style="western"><surname>Shapiro</surname><given-names>DJ</given-names> </name><name name-style="western"><surname>Hall</surname><given-names>M</given-names> </name><name name-style="western"><surname>Neuman</surname><given-names>MI</given-names> </name><etal/></person-group><article-title>Outpatient antibiotic use and treatment failure among children with pneumonia</article-title><source>JAMA Netw Open</source><year>2024</year><month>10</month><day>1</day><volume>7</volume><issue>10</issue><fpage>e2441821</fpage><pub-id pub-id-type="doi">10.1001/jamanetworkopen.2024.41821</pub-id><pub-id pub-id-type="medline">39470638</pub-id></nlm-citation></ref><ref id="ref23"><label>23</label><nlm-citation citation-type="journal"><person-group person-group-type="author"><name name-style="western"><surname>Fischer</surname><given-names>MA</given-names> </name><name name-style="western"><surname>Stedman</surname><given-names>MR</given-names> </name><name name-style="western"><surname>Lii</surname><given-names>J</given-names> </name><etal/></person-group><article-title>Primary medication non-adherence: analysis of 195,930 electronic prescriptions</article-title><source>J Gen Intern Med</source><year>2010</year><volume>25</volume><issue>4</issue><fpage>284</fpage><lpage>290</lpage><pub-id pub-id-type="doi">10.1007/s11606-010-1253-9</pub-id><pub-id pub-id-type="medline">20131023</pub-id></nlm-citation></ref><ref id="ref24"><label>24</label><nlm-citation citation-type="journal"><person-group person-group-type="author"><name name-style="western"><surname>Kajioka</surname><given-names>EH</given-names> </name><name name-style="western"><surname>Itoman</surname><given-names>EM</given-names> </name><name name-style="western"><surname>Li</surname><given-names>ML</given-names> </name><name name-style="western"><surname>Taira</surname><given-names>DA</given-names> </name><name name-style="western"><surname>Li</surname><given-names>GG</given-names> </name><name name-style="western"><surname>Yamamoto</surname><given-names>LG</given-names> </name></person-group><article-title>Pediatric prescription pick-up rates after ED visits</article-title><source>Am J Emerg Med</source><year>2005</year><month>07</month><volume>23</volume><issue>4</issue><fpage>454</fpage><lpage>458</lpage><pub-id pub-id-type="doi">10.1016/j.ajem.2004.10.015</pub-id><pub-id pub-id-type="medline">16032610</pub-id></nlm-citation></ref><ref id="ref25"><label>25</label><nlm-citation citation-type="journal"><person-group person-group-type="author"><name name-style="western"><surname>Youngster</surname><given-names>I</given-names> </name><name name-style="western"><surname>Gelernter</surname><given-names>R</given-names> </name><name name-style="western"><surname>Klainer</surname><given-names>H</given-names> </name><name name-style="western"><surname>Paz</surname><given-names>H</given-names> </name><name name-style="western"><surname>Kozer</surname><given-names>E</given-names> </name><name name-style="western"><surname>Goldman</surname><given-names>M</given-names> </name></person-group><article-title>Electronically monitored adherence to short-term antibiotic therapy in children</article-title><source>Pediatrics</source><year>2022</year><month>12</month><day>1</day><volume>150</volume><issue>6</issue><fpage>e2022058281</fpage><pub-id pub-id-type="doi">10.1542/peds.2022-058281</pub-id><pub-id pub-id-type="medline">36317476</pub-id></nlm-citation></ref><ref id="ref26"><label>26</label><nlm-citation citation-type="journal"><person-group person-group-type="author"><name name-style="western"><surname>Blecker</surname><given-names>S</given-names> </name><name name-style="western"><surname>Gannon</surname><given-names>M</given-names> </name><name name-style="western"><surname>De Leon</surname><given-names>S</given-names> </name><etal/></person-group><article-title>Practice facilitation for scale up of clinical decision support for hypertension management: study protocol for a cluster randomized control trial</article-title><source>Contemp Clin Trials</source><year>2023</year><month>06</month><volume>129</volume><fpage>107177</fpage><pub-id pub-id-type="doi">10.1016/j.cct.2023.107177</pub-id><pub-id pub-id-type="medline">37037392</pub-id></nlm-citation></ref></ref-list><app-group><supplementary-material id="app1"><label>Multimedia Appendix 1</label><p>Attrition diagram for encounter selection.</p><media xlink:href="jmir_v28i1e90954_app1.png" xlink:title="PNG File, 63 KB"/></supplementary-material><supplementary-material id="app2"><label>Multimedia Appendix 2</label><p>Distribution of unique patients and total encounters by number of encounters per patient (2930 patients; 3404 total encounters).</p><media xlink:href="jmir_v28i1e90954_app2.docx" xlink:title="DOCX File, 14 KB"/></supplementary-material></app-group></back></article>