How To: Advanced Data Retrieval with Named Queries
Use aggregates, filters, offsets, and grouped results to return exactly the values you need from a named query.
Use this guide when basic named queries are not enough.
These patterns help you return totals, target specific rows, and reuse one result set in multiple places.
Before you start
Make sure you already know the basic named query structure:
<queryname>YourQueryName</queryname>a valid
<soql>blockmerge fields in the form
{{!QueryName.FieldName}}
If you need a refresher, start with Creating Your First Named Query.
Pattern 1: Return aggregate values
Use aggregate SOQL when you need totals or counts in plain text.
<!--{{!
<lineitemsSOQL>
<queryname>OpportunityStats</queryname>
<soql>
SELECT COUNT(Id) cid, SUM(Amount) asum
FROM Opportunity
WHERE AccountId = '{{!Account.Id}}'
</soql>
</lineitemsSOQL>
}}-->Rules to remember:
Give each aggregate field an alias like
cidorasumReference the alias in your merge field, not the full function
Add number formatting after a space when needed
Pattern 2: Target a specific row with offset
Use offset when your named query returns several rows but you need one exact result.
offset="1" returns the first row.
offset="2" returns the second row.
Pattern 3: Reuse one query with filter and offset
Use filter when you want multiple output variations from one query result.
Define the filter inside the named query block.
Then call the filter in the merge field.
Rules to remember:
filter="1"points to<filter id="1">offset="1"returns the first matching rowYou can combine both on the same merge field
Pattern 4: Handle aggregate lookup fields carefully
Aggregate queries return aliases and grouped values.
That changes how you reference relationship fields.
Example query:
Use this output pattern:
In grouped aggregate results, reference the grouped field name directly.
Do not prepend the relationship path in the merge field.
Use {{!AccountCounts.Name}}, not {{!AccountCounts.Account.Name}}.
Common fixes
Blank output: Make sure the field appears in
SELECTWrong row: Check your
ORDER BYbefore usingoffsetFilter not working: Match the merge field
filtervalue to the<filter id>Aggregate error: Add aliases for aggregate functions
Relationship field is blank in an aggregate query: Use the grouped field name directly
Keep going
Review Named Query Working Examples for more copy-paste patterns
Review Named Query Structure for exact tag and merge field rules
Review Named Queries in DOCX and PPTX for format-specific wrapping syntax
Last updated
Was this helpful?

