Sql-server – PaaS Server – Random row order while using aggregate function with group by

azure-sql-databasesql server

Result set of a query with an aggregate function and group by (no order by specified) returns different result or at least in different order almost in each execution.

I have a database on Azure PaaS server and it's behaving weirdly. The query in issue is something like this:

SELECT TOP 100 "Org Unit", count(*) FROM "paas-server-12032019"."dbo"."testTable" GROUP BY "Org Unit"

When I check the "Org Unit" order, it's different each time. If I omit, count(*) and just keep the query as

SELECT TOP 100 "Org Unit" FROM "paas-server-12032019"."dbo"."testTable" GROUP BY "Org Unit"

It works as expected. Order of the record is consistent each time.
What I noticed

  • It happened with a specific database, I have another one and in there it works as expected.
  • Secondly, I think it has something to do when the column in group by is nvarchar(max)

I have a limited access currently to DB setup but wondering if there is anything that can cause this issue.

Any sort of help/discussion is deeply appreciated!

Best Answer

Without ORDER BY, you tell SQL Server that you don't care about the ordering.

SQL Server can do GROUP BY and aggregation internally by either sorting data or through hashing. SQL Server decides this based on what it expects to be the more efficient way. For your case when the order isn't consistent, SQL server found it more efficient to use hashing, apparently. You can see this in the execution plan.

Bottom line is, as always, if you want some specific order for the rows, then you need to use ORDER BY.