我們都知道在Oracle SQL語句中order by 是用來排序查詢出來的結果集的,而在Oracle中NULL值是一個很特殊的值,如果order by指定的列有NULL值,那排序結果又是怎樣的呢。
下面做一組實驗觀察一下order by時Oracle是怎么處理NULL的
版本11.2.0.4
1、創建測試表并插入測試數據
zx@ORCL>create table t (id number,name varchar2(10)); Table created. zx@ORCL>insert into t values(1,'zx'); 1 row created. zx@ORCL>insert into t values(2,'wl'); 1 row created. zx@ORCL>insert into t values(3,'zxt'); 1 row created. zx@ORCL>insert into t values(4,NULL); 1 row created. zx@ORCL>insert into t values(5,'yhz'); 1 row created. zx@ORCL>insert into t values(6,NULL); 1 row created. zx@ORCL>commit; Commit complete. zx@ORCL>select * from t; ID NAME ---------- ------------------------------ 1 zx 2 wl 3 zxt 4 5 yhz 6 6 rows selected.
2、測試order by
zx@ORCL>select * from t order by name asc; ID NAME ---------- ------------------------------ 2 wl 5 yhz 1 zx 3 zxt 6 4 6 rows selected. zx@ORCL>select * from t order by name desc; ID NAME ---------- ------------------------------ 4 6 3 zxt 1 zx 5 yhz 2 wl 6 rows selected.
看到不同的排序方式,NULL值所排序的位置不同。升序(asc)NULL排在最后,降序(desc)NULL排在最前。
我們再來看看官方文檔是怎么描述的
ASC | DESC Specify the ordering sequence (ascending or descending). ASC
is the default.
NULLS FIRST | NULLS LAST Specify whether returned rows containing nulls 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.
可以看到我們的實驗結果與官方文檔描述是一致的。而且還可以使用NULLS FIRST|NULLS LAST來決定NULL的值是排在最前還是排在最后。
3、再次做實驗驗證
zx@ORCL>select * from t order by name asc nulls first; ID NAME ---------- ------------------------------ 6 4 2 wl 5 yhz 1 zx 3 zxt 6 rows selected. zx@ORCL>select * from t order by name asc nulls last; ID NAME ---------- ------------------------------ 2 wl 5 yhz 1 zx 3 zxt 6 4 6 rows selected. zx@ORCL>select * from t order by name desc nulls first; ID NAME ---------- ------------------------------ 4 6 3 zxt 1 zx 5 yhz 2 wl 6 rows selected. zx@ORCL>select * from t order by name desc nulls last; ID NAME ---------- ------------------------------ 3 zxt 1 zx 5 yhz 2 wl 6 4 6 rows selected.
從結果可以看出使用NULLS FIRST|NULLS LAST可以直接控制NULL值在排序結果的首部還是尾部。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。