Some of you guys may not know that, so I’d like to share it.
If you need ordered data and your query does not have an ORDER BY clause, the data might return in any order. Yeah. It’s not guaranteed that it will return based in the order of the “primary key”.
So, you can’t assume that SQL Server has some “default” order. You might believe there is, because usually when you SELECT a specific table it will use the cluster index(PK) with identity IDs.
But, it’s not always the case. Check the following example:
The following query will run just fine, and “as expected”.
Now, let’s create the following index.
CREATE INDEX Test_RandomInt ON dbo.Test(RandomInt);
The same query executed before is now broken, just because SQL Server has decided to change the index in the execution plan .
I’m not saying that you should start sorting every single query (it’s very expensive performance wise). But, if you really need it, you must provide the ORDER BY clause.
It’s preferable to sort on the app side from a resource perspective, because generally it’s easier to add more servers or add more CPU and Memory to the application layer. It’s much more difficult, and expensive, to do so for the SQL servers.