十年網(wǎng)站開發(fā)經(jīng)驗(yàn) + 多家企業(yè)客戶 + 靠譜的建站團(tuán)隊(duì)
量身定制 + 運(yùn)營維護(hù)+專業(yè)推廣+無憂售后,網(wǎng)站問題一站解決
我們都知道在Oracle SQL語句中order by 是用來排序查詢出來的結(jié)果集的,而在Oracle中NULL值是一個很特殊的值,如果order by指定的列有NULL值,那排序結(jié)果又是怎樣的呢。
蒙城ssl適用于網(wǎng)站、小程序/APP、API接口等需要進(jìn)行數(shù)據(jù)傳輸應(yīng)用場景,ssl證書未來市場廣闊!成為創(chuàng)新互聯(lián)的ssl證書銷售渠道,可以享受市場價格4-6折優(yōu)惠!如果有意向歡迎電話聯(lián)系或者加微信:18980820575(備注:SSL證書合作)期待與您的合作!
下面做一組實(shí)驗(yàn)觀察一下order by時Oracle是怎么處理NULL的
版本11.2.0.4
1、創(chuàng)建測試表并插入測試數(shù)據(jù)
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.
可以看到我們的實(shí)驗(yàn)結(jié)果與官方文檔描述是一致的。而且還可以使用NULLS FIRST|NULLS LAST來決定NULL的值是排在最前還是排在最后。
3、再次做實(shí)驗(yàn)驗(yàn)證
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.
從結(jié)果可以看出使用NULLS FIRST|NULLS LAST可以直接控制NULL值在排序結(jié)果的首部還是尾部。