How does order by clause works if two values are equal?

后端 未结 3 756
北荒
北荒 2021-01-11 10:44

This is my NEWSPAPER table.

    National News   A   1
    Sports          D   1
    Editorials      A   12
    Business        E   1
    Weather         C            


        
相关标签:
3条回答
  • 2021-01-11 11:07

    If you need reliable, reproducible ordering to occur when two values in your ORDER BY clause's first column are the same, you should always provide another, secondary column to also order on. While you might be able to assume that they will sort themselves based on order entered (almost always the case to my knowledge, but be aware that the SQL standard does not specify any form of default ordering) or index, you never should (unless it is specifically documented as such for the engine you are using--and even then I'd personally never rely on that).

    Your query, if you wanted alphabetical sorting by feature within each page, should be:

    select feature,section,page from NEWSPAPER
    where section = 'F'
    order by page, feature;
    0 讨论(0)
  • 2021-01-11 11:18

    When you use the SELECT statement to query data from a table, the order which rows appear in the result set may not be what you expected.

    In some cases, the rows that appear in the result set are in the order that they are stored in the table physically. However, in case the query optimizer uses an index to process the query, the rows will appear as they are stored in the index key order. For this reason, the order of rows in the result set is undetermined or unpredictable.

    The query optimizer is a built-in software component in the database system that determines the most efficient way for an SQL statement to query the requested data.

    0 讨论(0)
  • 2021-01-11 11:19

    In relational databases, tables are sets and are unordered. The order by clause is used primarily for output purposes (and a few other cases such as a subquery containing rownum).

    This is a good place to start. The SQL standard does not specify what has to happen when the keys on an order by are the same. And this is for good reason. Different techniques can be used for sorting. Some might be stable (preserving original order). Some methods might not be.

    Focus on whether the same rows are in the sets, not their ordering. By the way, I would consider this an unfortunate example. The book should not have ambiguous sorts in its examples.

    0 讨论(0)
提交回复
热议问题