1

In SQL Server 2008, using distinct clause is always doing an implicit order by or I need to specify an order by for that? I want to be sure that using distinct put data in order.

Here you have an example, distinct is doing order by

create table #MyTable (id int)

insert into #MyTable values (3)
insert into #MyTable values (2)
insert into #MyTable values (8)

select distinct id from #MyTable
2
  • 2
    possible duplicate of Does sorting happens using distinct clause Commented Feb 12, 2014 at 13:20
  • 2
    SQL Server can use a hash for the DISTINCT in 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 T gives results 0,1,-1 for me. Commented Feb 12, 2014 at 13:23

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

Comments

1

DISTINCT clause has nothing to do with ordering records. You have to explicitly use ORDER BY clause for sorting.

select distinct id 
from #MyTable
Order By id

1 Comment

Even if your example happens to be sorted, you cannot depend on it. If you want it ordered you must use ORDER BY.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.