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

secooler發表於2010-01-30
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”的參考內容

摘錄在此:
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時的靈活性和可控性便可進一步得到加強。

Good luck.

secooler
10.01.30

-- The End --

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/519536/viewspace-626464/,如需轉載,請註明出處,否則將追究法律責任。

相關文章