For the complete documentation index, see llms.txt. This page is also available as Markdown.

How To: Chain Named Queries with queryname2

Use queryname2 when a second named query depends on a value returned by a first named query.

Use queryname2 when one named query depends on values returned by another named query.

This pattern lets you run a first query, save its result, and reuse that result inside a second query.

When to use queryname2

Use queryname2 when:

  • the second query needs a value returned by the first query

  • you want to avoid hard-coded values in the second query

  • one query result narrows the target record set for the next query

How queryname2 works

  1. Create the first named query with <queryname>.

  2. Place the dependent query later in the template with <queryname2>.

  3. Reference the first query's returned fields inside the second query's <soql> block.

  4. Output values from both queries with normal merge fields.

The first query must appear before the queryname2 block.

Example

queryname2-example.xml
<!--{{!
<lineitemsSOQL>
  <queryname>LatestOpp</queryname>
  <soql>
    SELECT Id, Name
    FROM Opportunity
    WHERE AccountId = '{{!Account.Id}}'
    ORDER BY CreatedDate DESC
    LIMIT 1
  </soql>
</lineitemsSOQL>
}}-->

<!--{{!
<lineitemsSOQL>
  <queryname2>TopLine</queryname2>
  <soql>
    SELECT Id, Quantity, TotalPrice
    FROM OpportunityLineItem
    WHERE OpportunityId = '{{!LatestOpp.Id}}'
    ORDER BY TotalPrice DESC
    LIMIT 1
  </soql>
</lineitemsSOQL>
}}-->

In this pattern:

  • LatestOpp stores the first query result

  • TopLine uses {{!LatestOpp.Id}} inside its SOQL

  • both results are available later in the template

Rules to remember

  • Put the first named query before the queryname2 block

  • Return every field you plan to reuse later in SELECT

  • Use stable keys like Id when possible

  • Add ORDER BY and LIMIT when more than one row could match

Common fixes

  • Second query is blank: Make sure the first query returns a row

  • Second query fails: Confirm the referenced field is included in the first query SELECT

  • Wrong record returned: Use a more specific filter, ORDER BY, or LIMIT

  • Microsoft template output prints as text: Wrap output fields in square brackets

Build and test the first named query by itself first.

Then add the queryname2 block once the first result is correct.

Keep going

Last updated

Was this helpful?