How to combine FOR VIEW and FOR REFERENCE?

I’m writing a fluent query builder and have hit a snag. While looking at the documentation for the FOR UPDATE clause, it has this snippet:

Consider using the FOR REFERENCE clause with the FOR VIEW clause to update recent usage data for retrieved objects.

Okay, cool, so that answers my question of if the two clauses are supported in tandem. But it does not specify how to combine them. I can’t seem to figure out the syntax. I tried all of the below queries with no luck.


Query

SELECT Id FROM Account FOR VIEW FOR REFERENCE

Error

unexpected token: REFERENCE


Query

SELECT Id FROM Account FOR REFERENCE FOR VIEW

Error

unexpected token: VIEW


Query

SELECT Id FROM Account FOR VIEW, FOR REFERENCE

Error

expecting right square bracket, found ‘,’


Query

SELECT Id FROM Account FOR VIEW, REFERENCE

Error

expecting right square bracket, found ‘,’


Also worth noting that either clause on its own can be combined with FOR UPDATE. At least…they work in Execute Anonymous. In the Query Editor, they still throw:

Unknown error parsing query

Valid Query

SELECT Id FROM Account FOR VIEW FOR UPDATE

Valid Query

SELECT Id FROM Account FOR REFERENCE FOR UPDATE

Answer

Based on the documentation of the syntax:

SELECT ***fieldList*** [subquery][...]
[TYPEOF typeOfField whenExpression[...] elseExpression END][...]
FROM objectType[,...] 
    [USING SCOPE filterScope]
[WHERE conditionExpression]
[WITH [DATA CATEGORY] filteringExpression]
[GROUP BY {fieldGroupByList|ROLLUP (fieldSubtotalGroupByList)|CUBE (fieldSubtotalGroupByList)} 
    [HAVING havingConditionExpression] ] 
[ORDER BY fieldOrderByList {ASC|DESC} [NULLS {FIRST|LAST}] ]
[LIMIT numberOfRowsToReturn]
[OFFSET numberOfRowsToSkip]
[FOR {VIEW  | REFERENCE}[,...] ]
      [ UPDATE {TRACKING|VIEWSTAT}[,...] ]

and the Typographical Conventions (including a relevant example that uses the same syntax)

[…] and [,…]

Square brackets containing an ellipsis indicate that the preceding element can be repeated up to the limit for the element. If a comma is also present, the repeated elements must be separated by commas. If the element is a list of choices grouped with curly braces, you can use items from the list in any order. For example, in the clause UPDATE {TRACKING|VIEWSTAT}[,...], the [,...] indicates that you can use TRACKING, VIEWSTAT, or both:

UPDATE TRACKING

UPDATE VIEWSTAT

UPDATE TRACKING, VIEWSTAT

This should be able to be executed as

FOR VIEW, REFERENCE

Unfortunately, this throws syntax errors in a v.39 org. Not sure about a v.40 org myself. Currently it looks like a few places have bad documentation around this, since the consideration to use them in conjunction is sprinkled throughout the docs for those optional clauses.

Attribution
Source : Link , Question Author : Adrian Larson , Answer Author : Mark Pond

Leave a Comment