Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does sorting happens using distinct clause

Tags:

sql

sql-server

Consider the below

empname salary
a   10000
b   5000
c   5000

If I do select distinct salary from @t

the output being

salary
5000
10000

It has been sorted ... Why so?

like image 886
aditi Avatar asked Jul 01 '11 11:07

aditi


People also ask

Does distinct SQL sort?

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.

What is the distinct clause used for?

The DISTINCT keyword in the SELECT clause is used to eliminate duplicate rows and display a unique list of values. In other words, the DISTINCT keyword retrieves unique values from a table.

Which of the clauses is used in sorting rows?

We can sort results in ascending or descending order with an ORDER BY clause in Select statement.

What is true about distinct clause?

SQL DISTINCT clause is used to remove the duplicates columns from the result set. The distinct keyword is used with select keyword in conjunction. It is helpful when we avoid duplicate values present in the specific columns/tables. The unique values are fetched when we use the distinct keyword.


1 Answers

Given that without an explicit ORDER BY the order of returned rows is undefined; the DISTICT probably causes a distinct-sort (look at the plan) operation which is probably why they are ordered in your example.

like image 128
Alex K. Avatar answered Sep 28 '22 03:09

Alex K.