简体   繁体   中英

How does Oracle SQL order rows when there is no ORDER BY

I have currently written SQL to bring back data in a select statement without using ORDER BY. From what I have read, the selection seems to be random? As I am trying to run tests on data that should be updated once selected, is there a way to 'predict' which entries will be returned by the select statement (and therefore should be modified)? My select statement is:

    SELECT x.FIELD_A,
           x.FIELD_B,
           x.FIELD_C,
           y.FIELD_D,
           y.FIELD_E,
           y.FIELD_F
    FROM TABLE_X x
             LEFT JOIN TABLE_Y Y ON x.FIELD_A = y.FIELD_G
    WHERE y.FIELD_G in ('xxx', 'yyy', 'zzz', 'www')
      AND y.FIELD_E = 'vvvv'
      AND y.FIELD_G IS NULL
      AND y.FIELD_H IS NULL
      AND y.FIED_I IS NULL
      AND x.FIELD_J IN ('uuu', 'ttt', 'sss', 'rrrr')
      AND y.FIELD_K_DATE > ADD_MONTHS(SYSDATE, -12)
      AND ROWNUM <= 20

How does Oracle SQL order rows when there is no ORDER BY?

It doesn't order them at all.

From a classic Tom Kyte article , and quoting his own book:

You should think of a heap organized table as a big unordered collection of rows. These rows will come out in a seemingly random order, and depending on other options being used (parallel query, different optimizer modes and so on), they may come out in a different order with the same query. Do not ever count on the order of rows from a query unless you have an ORDER BY statement on your query!

If you run your query several times today you may see the same results in the same order, but might not. You could run it a hundred times and perhaps get the same result each time, and think that means that's what it will always return. But if you run it again tomorrow it may or may not be the same. If you run it weeks or months or years in the future it still could be the same as you see today, but is increasingly likely not to be as other things change - including data volumes, statistics gathering, database upgrades or even potentially patching, and so on.

Without an order-by clause you are at the mercy of the optimiser and things even that can't control, potentially even down to the order blocks of data are read from disk.

So no, you can't predict which entries will be returned by your query. You will get 20 rows but which ones you get and what order those are in is non-deterministic.

If you need a predictable result you need to order the results before apply the rownum filter (or using fetch first ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM