While attempting to generate a seeded random ordering I noted this issue, now replicated both in SQL Server 2008 R2 (RTM) and on SEDE, i.e. SQL Server 2012 (SP1):
When you ORDER BY a VarBinary sub-SELECT field the ordering does not occur.
In the query plan (of SEDE above) you can see that there is no SORT for:
SELECT [id]
,y.x As ryx
,RAND(y.x) As yx
FROM #Test, (SELECT CONVERT(varbinary, NEWID()) As x) y
ORDER BY ryx
where as there is for all the other variations I tried (and you can see them in the SEDE query, as well as if you edit them to ORDER BY yx).
I've had a look at MSDN and only confirmed VarBinary use MACHINE collation when indexed.
Is this just a bug or a poorly documented feature? :-)
It is a bug.
See https://data.stackexchange.com/stackoverflow/query/162636/testing-sub-select-order-failure?opt.textResults=true&opt.withExecutionPlan=true
Example results:
In this query the
order byis clearly on the outside. It should not matter in what way the derived tablexis generated. Theorder bymust apply. The rows are returned in unsorted order.Report it to Microsoft Connect. It is an optimizer bug.