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:
| Form | When 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><< 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>
| Attribute | Required | Description |
|---|---|---|
name | Yes | Variable name used in rule expressions |
code | No | Name of a code list declared in <codeLists>. Without it, the variable reads every coded entry that matches its other filters |
select | Yes | Comma-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 |
order | Yes | Coded entry column to order results by, from the same set as select |
take | Yes | latest, earliest, or all |
clinicallyRelevantDate | No | Date range filter expression (e.g. GTEQ ACHV_DAT_MINUS_12_MONTHS AND LTEQ ACHV_DAT) |
endDate | No | Date 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 |
entityType | No | Comma-separated coded entry types to restrict to (e.g. problem) |
status | No | active or ended |
distinct | No | A 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 |
value1 | No | Filter expression on the entry's first numeric value (e.g. systolic blood pressure), same syntax as clinicallyRelevantDate (e.g. GTEQ 140) |
value2 | No | Filter expression on the entry's second numeric value (e.g. diastolic blood pressure) |
performedAtLocalOrganisation | No | TRUE to restrict to entries recorded at this practice |
encounterTypeCode | No | Name 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
| Element | Description |
|---|---|
<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 |
| Element | Values |
|---|---|
patientClinicalSex | male, 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
| Attribute | Required | Description |
|---|---|---|
status | No | Comma-separated prescription statuses to filter by, same values as prescriptionStatus |
type | No | Comma-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
| Attribute | Required | Description |
|---|---|---|
issueStatus | No | Comma-separated issue statuses to filter by: issued, not-issued |
Appointment variable
| Attribute | Required | Description |
|---|---|---|
status | No | Comma-separated appointment statuses to filter by: pending, started, seen, rescheduled, cancelled, did-not-attend, walked-out |
deliveryMode | No | Comma-separated delivery modes to filter by: face-to-face, home-visit, video, phone |
nhsNationalSlotTypeCategory | No | Comma-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 |
intendedStartDateTime | No | Date 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.
| Code | Category |
|---|---|
10101 | General Consultation Acute |
10108 | Home Visit |
10109 | Care Home Visit |
10110 | Group Consultation and Group Education |
10111 | Structured Medication Review |
10112 | Patient contact during Care Home Round |
10115 | Service provided by organisation external to the practice |
10116 | Non-contractual chargeable work |
10127 | General Consultation Routine |
10128 | Planned Clinics |
10129 | Planned Clinical Procedure |
10130 | Unplanned Clinical Activity |
10131 | Walk-in |
10132 | Clinical Triage |
10133 | Care Home Needs Assessment & Personalised Care and Support Planning |
10134 | Social Prescribing Service |
10135 | Care 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.
| Code | Category |
|---|---|
10102 | General Consultation Planned |
10103 | Scheduled / Planned Clinical Activity |
10104 | Scheduled / Planned Clinical Procedure |
10105 | Unscheduled / Unplanned clinical activity |
10106 | Walk In Clinic |
10107 | Triage |
10113 | Care Home Needs Assessment / Personalised Care / Support Planning |
10114 | Social Prescribing / Care Coordination Appointment |
10117 | Care 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"/>
| Attribute | Required | Description |
|---|---|---|
name | Yes | Variable name used in rule expressions |
select | Yes | Comma-separated clinical case columns to retrieve: patient_id, case_status, created_date_time, closed_date_time |
order | Yes | Clinical case column to order results by, from the same set as select |
take | Yes | latest, earliest, or all |
status | No | Comma-separated case statuses to filter by: open, closed |
type | No | Comma-separated clinical case type ids to filter by |
commissionedServiceOrganisation | No | Comma-separated commissioning organisation (ODS) codes to filter by |
commissionedServiceServiceIdentifier | No | Comma-separated commissioned service identifiers to filter by |
createdDateTime | No | Date 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) |
closedDateTime | No | Date 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"/>
| Attribute | Required | Description |
|---|---|---|
name | Yes | Variable name used in rule expressions |
select | Yes | Comma-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 |
order | Yes | Column to order results by, from the same set as select |
take | Yes | latest, earliest, or all |
status | No | Comma-separated statuses to filter by: active, removed |
pathway | No | Comma-separated clinical pathway ids to filter by |
currentStage | No | Comma-separated clinical pathway stage ids; keeps only pathways the patient is on that stage of now |
createdDateTime | No | Date range filter expression on when the patient was started on the pathway, same syntax as clinicallyRelevantDate above |
removedDateTime | No | Date 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"/>
| Attribute | Required | Description |
|---|---|---|
name | Yes | Variable name used in rule expressions |
select | Yes | Comma-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 |
order | Yes | Column to order results by, from the same set as select |
take | Yes | latest, earliest, or all |
pathway | No | Comma-separated clinical pathway ids to filter by |
fromStage | No | Comma-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 |
toStage | No | Comma-separated clinical pathway stage ids the patient moved into |
changedDateTime | No | Date 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
| Value | Meaning |
|---|---|
select | Include this patient in the cohort |
reject | Exclude this patient |
next-rule | Continue to the next rule |
Expressions
Expressions compare variable names (or their fields) using operators:
| Operator | Meaning |
|---|---|
NOTEQ | Not equal |
EQ | Equal, comparing both value and type, except that a number and a numeric string (such as a YYYYMMDD date) compare as numbers |
EQNS | Equal, comparing value only |
GT | Greater than |
GTEQ | Greater than or equal |
LT | Less than |
LTEQ | Less than or equal |
AND | Logical and |
OR | Logical or |
Special values:
| Token | Meaning |
|---|---|
NULL | No value / not found |
TRUE | Boolean true |
FALSE | Boolean false |
| Numeric literal | Integer 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:
| Form | Meaning |
|---|---|
VAR NOTEQ NULL | Variable has a result |
VAR.count GT 0 | Variable has at least one result |
VAR.value_1 GTEQ 48 | First numeric value meets threshold |
VAR.value_2 LTEQ 90 | Second numeric value (e.g. diastolic BP) |
CKDRES_LATEST GTEQ CKD_LATEST | Compares 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><< 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.