SOQL order by distance internal server error

Received a response from Salesforce:

Good Morning !

I have received an update from my tier -3 stating that "Binding variables are NOT allowed in ORDER BY clause, hence adding the following piece of code in an apex thrown Internal Server Error " DISTANCE(Location__r.BillingAddress, GEOLOCATION(:req.lat, :req.lng), 'mi') ASC.

However, adding something like the following works: ORDER BY StartDate ASC, DISTANCE(Location__r.BillingAddress, GEOLOCATION(43.075861, -87.882772), 'mi') ASC

There is already an idea about this: https://success.salesforce.com/ideaView?id=08730000000l56WAAQ

Please let me know in case of any queries.

Work around:

Convert the soql to a dynamic soql string and execute using Database.query();


Just to close the loop here, this behavior (not being able to bind variables in an ORDER BY clause) is documented in the Apex Developer Guide, though I didn't think to look there earlier. Emphasis mine:

Using Apex Variables in SOQL and SOSL Queries

SOQL and SOSL statements in Apex can reference Apex code variables and expressions if they’re preceded by a colon (:). This use of a local code variable within a SOQL or SOSL statement is called a bind. The Apex parser first evaluates the local variable in code context before executing the SOQL or SOSL statement. Bind expressions can be used as:

  • The search string in FIND clauses.
  • The filter literals in WHERE clauses.
  • The value of the IN or NOT IN operator in WHERE clauses, allowing filtering on a dynamic set of values. Note that this is of particular use with a list of IDs or Strings, though it works with lists of any type.
  • The division names in WITH DIVISION clauses.
  • The numeric value in LIMIT clauses.
  • The numeric value in OFFSET clauses.

Bind expressions can't be used with other clauses, such as INCLUDES.