Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does 'Select' always order by primary key?

A basic simple question for all of you DBA.

When I do a select, is it always guaranteed that my result will be ordered by the primary key, or should I specify it with an 'order by'?

I'm using Oracle as my DB.

like image 833
Thierry-Dimitri Roy Avatar asked May 05 '09 13:05

Thierry-Dimitri Roy


People also ask

Does SQL automatically ORDER BY primary key?

SQL Server automatically uses the primary key as the clustered index for the data. So the data is actually ordered by the primary key on the data pages (a query retrieving it will not return it in this order). In order words, the language may be a bit awkward, but this is a very valid question.

Does SQL SELECT guarantee order?

In the SQL world, order is not an inherent property of a set of data. Thus, you get no guarantees from your RDBMS that your data will come back in a certain order -- or even in a consistent order -- unless you query your data with an ORDER BY clause.

What does SQL ORDER BY default?

The ORDER BY statement in SQL is used to sort the fetched data in either ascending or descending according to one or more columns. By default ORDER BY sorts the data in ascending order. We can use the keyword DESC to sort the data in descending order and the keyword ASC to sort in ascending order.

Does ORDER BY column need to be in SELECT?

Notes. If SELECT DISTINCT is specified or if the SELECT statement contains a GROUP BY clause, the ORDER BY columns must be in the SELECT list. An ORDER BY clause prevents a SELECT statement from being an updatable cursor.


2 Answers

No, if you do not use "order by" you are not guaranteed any ordering whatsoever. In fact, you are not guaranteed that the ordering from one query to the next will be the same. Remember that SQL is dealing with data in a set based fashion. Now, one database implementation or another may happen to provide orderings in a certain way but you should never rely on that.

like image 186
BobbyShaftoe Avatar answered Oct 21 '22 18:10

BobbyShaftoe


When I do a select, is it always guaranteed that my result will be ordered by the primary key, or should I specify it with an 'order by'?

No, it's by far not guaranteed.

SELECT  *
FROM    table

most probably will use TABLE SCAN which does not use primary key at all.

You can use a hint:

SELECT  /*+ INDEX(pk_index_name) */
        *
FROM    table

, but even in this case the ordering is not guaranteed: if you use Enterprise Edition, the query may be parallelized.

This is a problem, since ORDER BY cannot be used in a SELECT clause subquery and you cannot write something like this:

SELECT  (
        SELECT  column
        FROM    table
        WHERE   rownum = 1
        ORDER BY
                other_column
        )
FROM    other_table
like image 33
Quassnoi Avatar answered Oct 21 '22 17:10

Quassnoi