Does 'Select' always order by primary key?

有些话、适合烂在心里 提交于 2020-01-19 01:28:13

问题


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.


回答1:


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.




回答2:


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



回答3:


No, ordering is never guaranteed unless you use an ORDER BY.

The order that rows are fetched is dependent on the access method (e.g. full table scan, index scan), the physical attributes of the table, the logical location of each row within the table, and other factors. These can all change even if you don't change your query, so in order to guarantee a consistent ordering in your result set, ORDER BY is necessary.




回答4:


It depends on your DB and also it depends on indexed fields.

For example, in my table Users every user has unique varchar(20) field - login, and primary key - id.

And "Select * from users" returns rowset ordered by login.




回答5:


If you desire specific ordering then declare it specifically using ORDER BY.

What if the table doesn't have primary key?




回答6:


If you want your results in a specific order, always specify an order by



来源:https://stackoverflow.com/questions/824855/does-select-always-order-by-primary-key

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!