17

In the absence of an Order By clause in a SOQL query, what order will Salesforce return results in?

Clearly if ordering is important then Order By should be specified, but I recently encountered a question about what the order would be if it was undefined.

My initial thoughts were Salesforce would return them in whatever order suited them. Much like SQL. For simple queries this would typically line up with the creation date descending and the Id ascending. For more complex queries it would depend on the joins being performed.

3 Answers 3

17

If you don't specify a where clause, the order of the returned rows is undefined, and a whole host of things can affect it including which columns you select,what your where clause is, if its a standard or custom object, if it has to do sharing checks, if it has to generate an API cursor and so on.

2
  • 1
    No, but when I execute the below query with no ORDER BY, I get the "same results" EVERY SINGLE TIME. So, there must be some default sort order.. SELECT Id, Name FROM User LIMIT 10 Commented Nov 17, 2014 at 2:39
  • 1
    The default order is the order that the db determines is the least amount of work. it does not represent any user determinable order. If you care about the order, add an order by clause.
    – superfell
    Commented Nov 17, 2014 at 3:44
18

According to the SOQL / SOSL Reference - SOQL SELECT Syntax (at the bottom of the page):

Ordered Results—There is no guarantee of the order of results unless you use an ORDER BY clause in a query.

1
  • 2
    +1 to this answer because it gives the supporting link to the fact it states.
    – love gupta
    Commented Apr 6, 2020 at 7:16
0

Per Salesforce's documentation, it is not guaranteed the order when the order by clause is missing, as Peter Knolle perfectly says (the link in his answer is out of date).

There’s no guarantee of the order of results unless you use an ORDER BY clause in a query.

2
  • Whilst this may theoretically answer the question, it would be preferable to include the essential parts of the answer here, and provide the link for reference.
    – identigral
    Commented Feb 7 at 7:55
  • 1
    You are completely right. I will provide a proper answer per your suggestion. Commented Feb 8 at 8:55

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .