Oracle對SQL排序後NULL值位置的“特殊關照”

來源:互聯網
上載者:User

Oralce對NULL值的排序後的位置有一個特殊的“關照”,這就是“NULLS FIRST”和“NULLS LAST”選項,使用這個選項便可以在SQL排序中強制指定NULL值出現的位置(是顯示在最前,還是顯示在最後)。示範並總結在此,供參考。

1.建立示範表T並初始化7條資料
sec@ora10g> create table t (x int);
sec@ora10g> insert into t values (1);
sec@ora10g> insert into t values (2);
sec@ora10g> insert into t values (3);
sec@ora10g> insert into t values (4);
sec@ora10g> insert into t values (null);
sec@ora10g> insert into t values (null);
sec@ora10g> insert into t values (null);
sec@ora10g> commit;

2.不加“關照”的order by升序排序效果--NULL值在後。
sec@ora10g> select * from t order by x;

         X
----------
         1
         2
         3
         4

 


7 rows selected.

3.不加“關照”的order by降序排序效果--NULL值在前。
sec@ora10g> select * from t order by x desc;

         X
----------

 

         4
         3
         2
         1

7 rows selected.

4.特殊“關照”的order by升序排序效果--NULL值在前。
sec@ora10g> select * from t order by x nulls first;

         X
----------

 

         1
         2
         3
         4

7 rows selected.

5.特殊“關照”的order by降序排序效果--NULL值在後。
sec@ora10g> select * from t order by x desc nulls last;

         X
----------
         4
         3
         2
         1

 


7 rows selected.

6.規律總結
1)不加“關照”的情況下,我們可以把那些NULL值假想為所有內容中值是最大的,因此,升序排序後NULL值在最後,倒序排序後NULL值在最前!
2)特殊“關照”的情況下,當指定“NULLS FIRST”時,無論是升序排序還是倒序排序,NULL值都會排列在最前面;當指定“NULLS LAST”時,無論是升序排序還是倒序排序,NULL值都會排列在最後面。

7.Oracle官方文檔中有關“NULLS FIRST | NULLS LAST”的參考內容
http://download.oracle.com/docs/cd/B19306_01/server.102/b14200/statements_10002.htm#i2171079
摘錄在此:
NULLS FIRST | NULLS LAST
Specify whether returned rows containing null values should appear first or last in the ordering sequence.
NULLS LAST is the default for ascending order, and NULLS FIRST is the default for descending order.

8.小結
通過這篇內容的介紹,我們可以看到Oracle的確是無微不至。有了這個NULL值位置的強制方法,我們在書寫SQL時的靈活性和可控性便可進一步得到加強。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.