Although the typical implementation of distinct is done using some kind of ordered data structure, the order it uses may not be the one you need.
There are:
- No guarantees that the data will be ordered any which way
- No guarantees that the same query on the same data later/tomorrow will return the data in the same (arbitrary) order
- No guarantees that the observed ordering will be consistent
The distinct clause does not imply ordering. As such, if you need the data ordered in a particular manner, you have to add an order by clause to the query.
Also note that one of the data structures that can be used is a hashtable/hashset, and though these may produce data that looks ordered if there are only a few values placed into them, with larger quantities this will break down, and regardless, this is implementation specific and undocumented. Do not rely on any such behavior.
DISTINCTin which case the results will almost certainly not be in the desired order. e.g.CREATE TABLE T(X INT);INSERT INTO T SELECT number%2 FROM master..spt_values;SELECT DISTINCT X FROM Tgives results0,1,-1for me.