Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does SELECT DISTINCT imply a sort of the results

Does including DISTINCT in a SELECT query imply that the resulting set should be sorted?

I don't think it does, but I'm looking for a an authoritative answer (web link).

I've got a query like this:

Select Distinct foo
From Bar

In oracle, the results are distinct but are not in sorted order. In Jet/MS-Access there seems to be some extra work being done to ensure that the results are sort. I'm assuming that oracle is following the spec in this case and MS Access is going beyond.

Also, is there a way I can give the table a hint that it should be sorting on foo (unless otherwise specified)?

like image 386
S Ennis Avatar asked Mar 27 '09 21:03

S Ennis


People also ask

What does SELECT distinct does?

The SELECT DISTINCT statement is used to return only distinct (different) values. Inside a table, a column often contains many duplicate values; and sometimes you only want to list the different (distinct) values.

Does SELECT distinct affect performance?

Yes, basically it has to sort the results and then re-processed to eliminate the duplicates. This cull could also be being done during the sort, but we can only speculate as to how exactly the code works in the background. You could try and improve the performance by creating an index composed of all three (3) fields.

Is there any difference in how distinct and unique affect results of a query?

The main difference between unique and distinct is that UNIQUE is a constraint that is used on the input of data and ensures data integrity. While DISTINCT keyword is used when we want to query our results or in other words, output the data.

What is the difference between SELECT and SELECT distinct?

SELECT * will select all the columns from the tables in the FROM clause; SELECT DISTINCT * will find all unique combinations of row data for tables in the FROM clause. DISTINCT forces a sort and unique filtering operations making it far slower for large data.


2 Answers

From the SQL92 specification:

If DISTINCT is specified, then let TXA be the result of eliminating redundant duplicate values from TX. Otherwise, let TXA be TX.

...

4) If an is not specified, then the ordering of the rows of Q is implementation-dependent.

Ultimately the real answer is that DISTINCT and ORDER BY are two separate parts of the SQL statement; If you don't have an ORDER BY clause, the results by definition will not be specifically ordered.

like image 148
Chris Shaffer Avatar answered Sep 22 '22 15:09

Chris Shaffer


No. There are a number of circumstances in which a DISTINCT in Oracle does not imply a sort, the most important of which is the hashing algorithm used in 10g+ for both group by and distinct operations.

Always specify ORDER BY if you want an ordered result set, even in 9i and below.

like image 40
David Aldridge Avatar answered Sep 19 '22 15:09

David Aldridge