Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
650 views
in Technique[技术] by (71.8m points)

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

This is my NEWSPAPER table.

    National News   A   1
    Sports          D   1
    Editorials      A   12
    Business        E   1
    Weather         C   2
    Television      B   7
    Births          F   7
    Classified      F   8
    Modern Life     B   1
    Comics          C   4
    Movies          B   4
    Bridge          B   2
    Obituaries      F   6
    Doctor Is In    F   6

When i run this query

select feature,section,page from NEWSPAPER
where section = 'F'
order by page;

It gives this output

Doctor Is In    F   6
Obituaries      F   6
Births          F   7
Classified      F   8

But in Kevin Loney's Oracle 10g Complete Reference the output is like this

Obituaries      F   6
Doctor Is In    F   6
Births          F   7
Classified      F   8

Please help me understand how is it happening?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...