Skip to main content
Resource Publishing

Patient Query Language

A patient query is the engine behind custom reports and future action rules. It defines which patients belong to a cohort by combining a starting population, code lists, variables derived from patient data, and if/then/else rules that select or reject each patient.

A query decides cohort membership, one patient at a time. Aggregating over the resulting cohort is the job of the report or dashboard that consumes it.

Structure​

Every patient query has four sections in order:

<patientQuery>
<name>...</name>
<description>...</description>
<population>...</population> <!-- starting cohort -->
<codeLists>...</codeLists> <!-- named groups of SNOMED CT concept IDs -->
<variables>...</variables> <!-- named values derived from patient data -->
<rules>...</rules> <!-- select or reject logic -->
</patientQuery>

Population​

The <population> element specifies the starting set of patients the query evaluates against. Use one of four forms:

FormWhen to use
<patientQueryReference>Reference a published patient query by identifier
<patientQuery>Embed a sub-query inline (recursive)
<patientReportReference>Use the patient set from a published report
<patientIdList>Explicit list of patient UUIDs

The most common form is <patientQueryReference>, referencing a published query that defines the base cohort (for example, all registered patients or all patients with a specific condition).

<population>
<patientQueryReference>nhs-england/ALL</patientQueryReference>
</population>

Code lists​

Code lists are named sets of clinical or medicinal concept identifiers. Declare them in <codeLists>, then reference them by name from variable attributes. Each <codeList> has a <name> followed by one of two payloads:

<codeLists>
<!-- Expressions evaluated against the terminology on every run -->
<codeList>
<name>ASTHMA</name>
<codeListDefinition>
<rules>
<inclusion>&lt;&lt; 195967001 |Asthma|</inclusion>
</rules>
</codeListDefinition>
</codeList>

<!-- An explicit list of identifiers, not expanded -->
<codeList>
<name>SPECIFIC_CODES</name>
<fixedCodeList>
<codes>
<code>73211009</code>
<code>44054006</code>
</codes>
</fixedCodeList>
</codeList>
</codeLists>

See Code Lists for the full expression syntax, how inclusions and exclusions combine, dm+d and BNF expressions, every variable attribute that accepts a code list, and what is validated when.

Variables​

Variables capture named values from patient data. They are referenced by name in rule expressions.

Coded entry variable​

Finds coded entries in the patient's care record matching a code list. The result is a date (or set of dates) that can be tested in rules.

<variables>
<codedEntryVariable
name="DIABETES_DAT"
code="DIABETES"
select="clinically_relevant_date"
order="clinically_relevant_date"
take="latest"/>
</variables>
AttributeRequiredDescription
nameYesVariable name used in rule expressions
codeNoName of a code list declared in <codeLists>. Without it, the variable reads every coded entry that matches its other filters
selectYesComma-separated coded entry columns to retrieve (e.g. clinically_relevant_date, value_1, code). Each column must be one the schema allows; an unrecognised name is rejected when you save
orderYesCoded entry column to order results by, from the same set as select
takeYeslatest, earliest, or all
clinicallyRelevantDateNoDate range filter expression (e.g. GTEQ ACHV_DAT_MINUS_12_MONTHS AND LTEQ ACHV_DAT)
endDateNoDate range filter expression on the entry's end date, same syntax as clinicallyRelevantDate (e.g. GT ACHV_DAT_MINUS_1_YEAR). Only entries that have ended, such as an ended problem, have one
entityTypeNoComma-separated coded entry types to restrict to (e.g. problem)
statusNoactive or ended
distinctNoA coded entry column, for take="all" only. Keeps one entry per value of that column for each patient, so distinct="encounter_id" with .count counts consultations rather than their entries
value1NoFilter expression on the entry's first numeric value (e.g. systolic blood pressure), same syntax as clinicallyRelevantDate (e.g. GTEQ 140)
value2NoFilter expression on the entry's second numeric value (e.g. diastolic blood pressure)
performedAtLocalOrganisationNoTRUE to restrict to entries recorded at this practice
encounterTypeCodeNoName of a code list declared in <codeLists>; restricts results to entries recorded during an encounter of one of these types

The column names accepted by select and order are fixed per variable type and are listed in the custom report schema. A name outside that set is rejected when the report is saved, rather than failing later when the report runs.

clinicallyRelevantDate, endDate, value1, and value2 need an operator: they take the same left-implicit expression syntax as a rule's <if> but without the left value, so value1="0" alone is not valid, write value1="EQ 0". Prescription, prescription issue, and appointment variables' own date/value attributes (startDate, endDate, lastIssueDate, discontinuedDate, issueDate, supplyEndDate, quantityValue, intendedStartDateTime, intendedEndDateTime, bookedDateTime) follow the same rule. An invalid one is rejected when the report is saved.

Fixed date variable​

A fixed date value, either hardcoded or supplied at runtime:

<!-- Hardcoded dates, YYYY-MM-DD format -->
<fixedDate name="START_DAT">2026-06-01</fixedDate>
<fixedDate name="END_DAT">2026-06-30</fixedDate>

<!-- Runtime value (supplied when the report is run) -->
<fixedDate name="ACHV_DAT" runtimeValue="true"/>

Derived fixed date​

Compute a date by adding or subtracting a period from a fixed date variable:

<derivedFixedDate name="ACHV_DAT_MINUS_12_MONTHS" fixedDateName="ACHV_DAT" operation="-12 months"/>
<derivedFixedDate name="ACHV_DAT_MINUS_15_MONTHS" fixedDateName="ACHV_DAT" operation="-15 months"/>
<derivedFixedDate name="YEAR_START" fixedDateName="ACHV_DAT" operation="first day of this year"/>

Patient demographics variables​

ElementDescription
<patientClinicalSex name="..."/>Patient's clinical sex
<patientNamedGp name="..."/>Patient's named GP
<patientRegisteredGpPractice name="..."/>Patient's registered GP practice ODS code
<patientRegisteredGpPracticeName name="..."/>Patient's registered GP practice name, looked up from ODS (falls back to the ODS code)
<patientEntryDate name="..." patientField="date_of_birth|death_date"/>Date from demographics
<patientAge name="..." atDate="DATE_VAR" type="years|months"/>Age at a given date
ElementValues
patientClinicalSexmale, female, unknown

Registration variable​

Retrieves registration record data:

<patientRegistrationVariable
name="CURRENT_REG"
select="start_date,registration_type"
order="start_date"
take="latest"/>

Prescription and appointment variables​

<prescriptionVariable
name="STATIN_RX"
productCode="STATINS"
select="status,start_date"
order="start_date"
take="latest"
status="authorised"/>

<appointmentVariable
name="LAST_APPT"
select="intended_start_date_time"
order="intended_start_date_time"
take="latest"
status="pending"/>

A prescriptionVariable reports a prescription. Quantity is recorded on each issue, not on the prescription, so lastIssueFields adds fields from the prescription's own last issue, the issued one with the latest issue date: lastIssueFields="quantity_value,quantity_unit_description" gives each prescription last_issue_quantity_value and last_issue_quantity_unit_description. It takes an issue's own columns, the same as a prescriptionIssueVariable's select without the prescription_ fields. A prescription with nothing issued has these fields empty.

Prescription variable​

AttributeRequiredDescription
statusNoComma-separated prescription statuses to filter by, same values as prescriptionStatus
typeNoComma-separated prescription types to filter by, same values as prescriptionType

A prescriptionIssueVariable reports one issue (one supply) of a prescription. Alongside the issue's own columns it can select (and order by) fields from the prescription it belongs to: prescription_dosage_instruction, prescription_type, prescription_status and prescription_authorised_date. These come from the issue's own prescription, so they stay consistent with the rest of that issue's row. It can also filter on the parent prescription: prescriptionStatus keeps only issues whose prescription has one of the given statuses (authorised, discontinued, reauthorised, requires-review), and prescriptionType only those of a given type (acute, repeat, variable-repeat, repeat-dispensing).

Prescription issue variable​

AttributeRequiredDescription
issueStatusNoComma-separated issue statuses to filter by: issued, not-issued

Appointment variable​

AttributeRequiredDescription
statusNoComma-separated appointment statuses to filter by: pending, started, seen, rescheduled, cancelled, did-not-attend, walked-out
deliveryModeNoComma-separated delivery modes to filter by: face-to-face, home-visit, video, phone
nhsNationalSlotTypeCategoryNoComma-separated NHS national slot type category codes to filter by. Takes the 5-digit code, not the category name. The first digit is the setting: 1 General Practice, 2 Primary Care Network, 3 Extended Access Provision, 4 Other. The categories are listed below
intendedStartDateTimeNoDate range filter expression on the appointment's intended start date and time, same syntax as clinicallyRelevantDate

NHS national slot type categories​

The categories that can be picked on an appointment type. Codes shown are for General Practice. For another setting, change the first digit: 20101 is General Consultation Acute in a Primary Care Network. Primary Care Network also has 20107, Triage. In Other, Unplanned Clinical Activity is 40140, not 40130.

CodeCategory
10101General Consultation Acute
10108Home Visit
10109Care Home Visit
10110Group Consultation and Group Education
10111Structured Medication Review
10112Patient contact during Care Home Round
10115Service provided by organisation external to the practice
10116Non-contractual chargeable work
10127General Consultation Routine
10128Planned Clinics
10129Planned Clinical Procedure
10130Unplanned Clinical Activity
10131Walk-in
10132Clinical Triage
10133Care Home Needs Assessment & Personalised Care and Support Planning
10134Social Prescribing Service
10135Care Related Encounter but does not fit into any other category

Retired NHS national slot type categories​

No longer offered on an appointment type, but still accepted by the filter. Codes shown are for General Practice; change the first digit for another setting.

CodeCategory
10102General Consultation Planned
10103Scheduled / Planned Clinical Activity
10104Scheduled / Planned Clinical Procedure
10105Unscheduled / Unplanned clinical activity
10106Walk In Clinic
10107Triage
10113Care Home Needs Assessment / Personalised Care / Support Planning
10114Social Prescribing / Care Coordination Appointment
10117Care Related Encounter but does not fit into any of the above

Clinical case variable​

Retrieves clinical case data (the case's status, type, and commissioned service) from the reporting database:

<clinicalCaseVariable
name="OPEN_ADHD_CASE"
select="case_status"
order="created_date_time"
take="latest"
status="open"
type="019e2f4a-3b8c-7c1a-9d2e-4f5a6b7c8d9e"/>
AttributeRequiredDescription
nameYesVariable name used in rule expressions
selectYesComma-separated clinical case columns to retrieve: patient_id, case_status, created_date_time, closed_date_time
orderYesClinical case column to order results by, from the same set as select
takeYeslatest, earliest, or all
statusNoComma-separated case statuses to filter by: open, closed
typeNoComma-separated clinical case type ids to filter by
commissionedServiceOrganisationNoComma-separated commissioning organisation (ODS) codes to filter by
commissionedServiceServiceIdentifierNoComma-separated commissioned service identifiers to filter by
createdDateTimeNoDate range filter expression on the case's created date, same syntax as clinicallyRelevantDate above (e.g. GTEQ ACHV_DAT_MINUS_12_MONTHS AND LTEQ ACHV_DAT)
closedDateTimeNoDate range filter expression on the case's closed date, same syntax as createdDateTime

type filters against the clinical case type table, joined only when the attribute is present. commissionedServiceOrganisation and commissionedServiceServiceIdentifier both filter against the commissioned service table, sharing a single join when both are given.

Clinical pathway variable​

Retrieves the clinical pathways a patient has been started on, with each pathway's status and current stage, from the reporting database:

<clinicalPathwayVariable
name="ON_AUTISM_PATHWAY"
select="pathway_status,created_date_time"
order="created_date_time"
take="latest"
status="active"
pathway="019e2f4a-3b8c-7c1a-9d2e-4f5a6b7c8d9e"/>
AttributeRequiredDescription
nameYesVariable name used in rule expressions
selectYesComma-separated columns to retrieve: patient_id, pathway_status, created_date_time, removed_date_time, pathway_name, current_stage_name, current_stage_position, clinical_case_id, case_type_name, commissioned_service_name, commissioning_organisation_name. current_stage_position is empty when the stage is archived. The case columns are empty when the pathway isn't part of a case, and the commissioned service columns are empty when the case has no commissioned service
orderYesColumn to order results by, from the same set as select
takeYeslatest, earliest, or all
statusNoComma-separated statuses to filter by: active, removed
pathwayNoComma-separated clinical pathway ids to filter by
currentStageNoComma-separated clinical pathway stage ids; keeps only pathways the patient is on that stage of now
createdDateTimeNoDate range filter expression on when the patient was started on the pathway, same syntax as clinicallyRelevantDate above
removedDateTimeNoDate range filter expression on when the patient was removed from the pathway, same syntax as createdDateTime

Clinical pathway stage change variable​

Retrieves every move a patient has made between stages of a clinical pathway, including the stage they started on. Use it to ask when a patient reached a stage, even if they have since moved on:

<clinicalPathwayStageChangeVariable
name="REACHED_DIAGNOSIS"
select="changed_date_time"
order="changed_date_time"
take="earliest"
pathway="019e2f4a-3b8c-7c1a-9d2e-4f5a6b7c8d9e"
toStage="019e2f4b-8a1d-7e2f-b3c4-5d6e7f8a9b0c"
changedDateTime="GTEQ ACHV_DAT_MINUS_12_MONTHS AND LTEQ ACHV_DAT"/>
AttributeRequiredDescription
nameYesVariable name used in rule expressions
selectYesComma-separated columns to retrieve: patient_id, changed_date_time, from_stage_name, to_stage_name. from_stage_name is empty for the stage the patient started on
orderYesColumn to order results by, from the same set as select
takeYeslatest, earliest, or all
pathwayNoComma-separated clinical pathway ids to filter by
fromStageNoComma-separated clinical pathway stage ids the patient moved out of. Removing a patient from a pathway isn't a stage change, so it isn't included
toStageNoComma-separated clinical pathway stage ids the patient moved into
changedDateTimeNoDate range filter expression on when the stage change happened, same syntax as clinicallyRelevantDate above

Patient query variable​

Use the result of a published patient query as a boolean variable:

<patientQuery name="IN_REGISTER" queryIdentifier="nhs-england/DIABETES_QOF_REGISTER"/>

Rules​

Rules evaluate in order. Each rule has an <if> expression and <then>/<else> outcomes.

Outcomes​

ValueMeaning
selectInclude this patient in the cohort
rejectExclude this patient
next-ruleContinue to the next rule

Expressions​

Expressions compare variable names (or their fields) using operators:

OperatorMeaning
NOTEQNot equal
EQEqual, comparing both value and type, except that a number and a numeric string (such as a YYYYMMDD date) compare as numbers
EQNSEqual, comparing value only
GTGreater than
GTEQGreater than or equal
LTLess than
LTEQLess than or equal
ANDLogical and
ORLogical or

Special values:

TokenMeaning
NULLNo value / not found
TRUEBoolean true
FALSEBoolean false
Numeric literalInteger or decimal (e.g. 23, 10.5)

TRUE and FALSE are values to compare against, not conditions on their own. A bare <if>TRUE</if> throws Missing conditional operator. To select every patient, compare a field that is always present instead, for example <if>patientClinicalSex NOTEQ NULL</if>.

Variable fields are accessed with dot notation:

FormMeaning
VAR NOTEQ NULLVariable has a result
VAR.count GT 0Variable has at least one result
VAR.value_1 GTEQ 48First numeric value meets threshold
VAR.value_2 LTEQ 90Second numeric value (e.g. diastolic BP)
CKDRES_LATEST GTEQ CKD_LATESTCompares one variable with another

Parentheses group sub-expressions:

<if>(SYSTOLIC_DAT.value_1 GTEQ 140 OR DIASTOLIC_DAT.value_2 GTEQ 90) AND REG_DAT NOTEQ NULL</if>

The FIND ANY prefix tests whether any instance of a multi-value variable satisfies a condition:

<if>FIND ANY APPTS WHERE APPTS.status EQ pending</if>

Every comparison needs a left value, an operator, and a right value. Two comparisons need an explicit AND/OR between them: <if>A NOTEQ NULL B NOTEQ NULL</if> (no connector) is rejected, as is an AND/OR with no comparison on one side of it. These are checked when the report is saved, rather than failing when the report runs.

How expressions are evaluated​

Four evaluation rules determine what an expression actually selects. Each of them produces a valid cohort rather than an error, so getting one wrong is silent.

AND and OR evaluate strictly left to right. There is no operator precedence: AND does not bind more tightly than OR. A OR B AND C is evaluated as (A OR B) AND C, not as A OR (B AND C). Always parenthesise when both operators appear in one expression.

<!-- Evaluated as (ASTHMA_DAT NOTEQ NULL OR COPD_DAT NOTEQ NULL) AND REVIEW_DAT EQ NULL -->
<if>ASTHMA_DAT NOTEQ NULL OR COPD_DAT NOTEQ NULL AND REVIEW_DAT EQ NULL</if>

<!-- To attach the review-date condition to COPD only, group it explicitly -->
<if>ASTHMA_DAT NOTEQ NULL OR (COPD_DAT NOTEQ NULL AND REVIEW_DAT EQ NULL)</if>

Comparisons against a missing value return false. If either side has no value, every operator except EQ and NOTEQ returns false. A threshold test therefore fails both when the value misses the threshold and when there is no value at all:

<!-- False when the value is 100 or more, AND false when there is no value at all -->
<if>HBA1C.value_1 LT 100</if>

<!-- Test for presence first when the difference matters -->
<if>HBA1C NOTEQ NULL AND HBA1C.value_1 LT 100</if>

Comparisons over multiple values are existential. A variable declared with take="all" holds several results, and a comparison is true if any one of them satisfies it. This matters most for negative comparisons: READINGS.value_1 NOTEQ 5 is true when at least one recorded value is not 5, which is not the same as "none of them is 5".

NOTEQ cannot express "no result matches". Narrow the variable with its own filter attributes so a matching result is never returned, then test it for NULL:

<variables>
<!-- Only returns a result if a qualifying entry exists -->
<codedEntryVariable name="REVIEW_DAT" code="REVIEW_CODES"
select="clinically_relevant_date"
order="clinically_relevant_date"
take="latest"
clinicallyRelevantDate="GTEQ ACHV_DAT_MINUS_12_MONTHS AND LTEQ ACHV_DAT"/>
</variables>
<rules>
<rule>
<!-- No review in the last 12 months -->
<if>REVIEW_DAT EQ NULL</if>
<then>select</then>
<else>reject</else>
</rule>
</rules>

This is the general pattern for any "patient does not have" cohort. Prefer it to NOTEQ whenever the variable can hold more than one result.

EQ is strict, EQNS is not. EQ compares value and type; EQNS compares value only. Whole numbers are converted to decimals first, so numeric literals behave the same either way, but a value whose recorded type you do not control may not match under EQ.

Counting a patient's results​

count is the one function available in an expression. Declare the variable with take="all", narrow it with the variable's own filter attributes, then threshold the count in the rule:

<variables>
<fixedDate runtimeValue="true" name="ACHV_DAT"/>
<derivedFixedDate name="ACHV_DAT_MINUS_12_MONTHS" fixedDateName="ACHV_DAT" operation="-12 months"/>

<prescriptionIssueVariable name="DRUG_X_ISSUES" productCode="DRUG_X_COD"
select="patient_id" order="issue_date" take="all"
issueDate="GT ACHV_DAT_MINUS_12_MONTHS"/>
</variables>
<rules>
<rule>
<!-- More than four issues in the last 12 months -->
<if>DRUG_X_ISSUES.count GT 4</if>
<then>select</then>
<else>reject</else>
</rule>
</rules>

Filter on the variable rather than adding a second variable to do the narrowing. The count then covers exactly the rows that survived the filter.

A variable with no matching results is null rather than an empty list, so its count is null rather than zero. Threshold comparisons are unaffected, since GT and GTEQ against null return false and the patient is correctly not selected. count EQ 0 is the exception and never matches any patient, because null is not equal to zero. Test for none with EQ NULL:

<!-- Never matches any patient -->
<if>DRUG_X_ISSUES.count EQ 0</if>

<!-- No issues in the last 12 months -->
<if>DRUG_X_ISSUES EQ NULL</if>

Describing rules and variables​

A rule can carry a <description> element and any variable can carry a description attribute. Both are optional. When someone asks why a patient is or isn't in a report, the debug view shows these descriptions in place of the raw <if> expression and the variable name alone.

<variables>
<fixedDate name="ACHV_DAT" runtimeValue="true" description="The date the report is run"/>
<patientAge name="AGE" atDate="ACHV_DAT" description="Age on the run date"/>
</variables>
<rules>
<rule>
<description>Select patients aged 75 or over.</description>
<if>AGE GTEQ 75</if>
<then>select</then>
<else>reject</else>
</rule>
</rules>

Descriptions don't change which patients a query selects.

Complete example​

A patient report selecting patients who have a diabetes coded entry in the last 12 months:

<?xml version="1.0" encoding="UTF-8"?>
<patientReport schemaVersion="3">
<name>Patients with Recent Diabetes Review</name>
<rows>
<patientQuery>
<name>Diabetes cohort</name>
<description>Patients with a diabetes coded entry in the last 12 months.</description>
<population>
<patientQueryReference>nhs-england/ALL</patientQueryReference>
</population>
<codeLists>
<codeList>
<name>DIABETES</name>
<codeListDefinition>
<rules>
<inclusion>&lt;&lt; 73211009 |Diabetes mellitus|</inclusion>
</rules>
</codeListDefinition>
</codeList>
</codeLists>
<variables>
<fixedDate name="ACHV_DAT" runtimeValue="true"/>
<derivedFixedDate name="ACHV_DAT_MINUS_12_MONTHS"
fixedDateName="ACHV_DAT"
operation="-12 months"/>
<codedEntryVariable name="DIABETES_DAT" code="DIABETES"
select="clinically_relevant_date"
order="clinically_relevant_date"
take="latest"
clinicallyRelevantDate="GTEQ ACHV_DAT_MINUS_12_MONTHS AND LTEQ ACHV_DAT"/>
</variables>
<rules>
<rule>
<if>DIABETES_DAT NOTEQ NULL</if>
<then>select</then>
<else>reject</else>
</rule>
</rules>
</patientQuery>
</rows>
<columns>
<demographicInformationColumn headerName="Patient" value="patientName"/>
<demographicInformationColumn headerName="NHS Number" value="patientNhsNumber"/>
<demographicInformationColumn headerName="Date of Birth" value="patientDateOfBirth"/>
<demographicInformationColumn headerName="Named GP" value="namedGP"/>
</columns>
</patientReport>

What a query cannot express​

Arithmetic. There are no arithmetic operators. You cannot add, subtract, multiply or divide values in an expression, compute a ratio or percentage, or sum a value across a patient's entries. Scores and indices that combine several recorded values into one number cannot be calculated inside a query.

Some variable types do compute a value before any comparison happens: date variables derive new dates via operation, and <patientAge> derives the patient's age at a date. Both derive from dates the record already holds. There is no equivalent for recorded values.

If you need a computed value, calculate it in your own system and record it against the patient as a coded entry with a numeric value. The query can then filter on it like any other observation.

The size of a change. You can declare one variable for the earliest result and another for the latest and compare them, so "the most recent value is higher than the first" is expressible. The magnitude is not, because there is no subtraction.

Text matching. There is no substring, prefix, wildcard or pattern operator, and no way to search free text, consultation notes or document content. Values in an expression may contain letters, digits, underscores, dots and hyphens only, so quoted strings and values containing spaces are not supported. Match on clinical meaning using code lists instead, which expand through the SNOMED CT hierarchy and are both more precise and more complete than a text match.

Units. Value filters compare the recorded number only. Units are not part of the comparison and are not converted, so a query cannot assert that a value is in the unit the threshold assumes. Scope value comparisons with a code list precise enough that every matching entry is recorded in the same unit.