阿里云-云小站(无限量代金券发放中)
【腾讯云】云服务器、云数据库、COS、CDN、短信等热卖云产品特惠抢购

Oracle order by子句对NULL的排序

120次阅读
没有评论

共计 2115 个字符,预计需要花费 6 分钟才能阅读完成。

我们都知道在 Oracle SQL 语句中 order by 是用来排序查询出来的结果集的,而在 Oracle 中 NULL 值是一个很特殊的值,如果 order by 指定的列有 NULL 值,那排序结果又是怎样的呢。

下面做一组实验观察一下 order by 时 Oracle 是怎么处理 NULL 的
版本 11.2.0.4
1、创建测试表并插入测试数据
linuxidc@ORCL>create table t (id number,name varchar2(10));
 
Table created. 
 
linuxidc@ORCL>insert into t values(1,’zx’);
 
1 row created. 
 
linuxidc@ORCL>insert into t values(2,’wl’);
 
1 row created. 
 
linuxidc@ORCL>insert into t values(3,’zxt’);
 
1 row created. 
 
linuxidc@ORCL>insert into t values(4,NULL);
 
1 row created. 
 
linuxidc@ORCL>insert into t values(5,’yhz’);
 
1 row created. 
 
linuxidc@ORCL>insert into t values(6,NULL);
 
1 row created. 
 
linuxidc@ORCL>commit;
 
Commit complete. 
 
linuxidc@ORCL>select * from t;
 
    ID NAME
———- ——————————
    1 zx
    2 wl
    3 zxt
    4
    5 yhz
    6
 
6 rows selected.

2、测试 order by

linuxidc@ORCL>select * from t order by name asc;
 
    ID NAME
———- ——————————
    2 wl
    5 yhz
    1 zx
    3 zxt
    6
    4
 
6 rows selected. 
 
linuxidc@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、再次做实验验证
linuxidc@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. 
 
linuxidc@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. 
 
linuxidc@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. 
 
linuxidc@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.

更多 Oracle 相关信息见Oracle 专题页面 http://www.linuxidc.com/topicnews.aspx?tid=12

本文永久更新链接地址:http://www.linuxidc.com/Linux/2017-01/139782.htm

正文完
星哥说事-微信公众号
post-qrcode
 0
星锅
版权声明:本站原创文章,由 星锅 于2022-01-22发表,共计2115字。
转载说明:除特殊说明外本站文章皆由CC-4.0协议发布,转载请注明出处。
【腾讯云】推广者专属福利,新客户无门槛领取总价值高达2860元代金券,每种代金券限量500张,先到先得。
阿里云-最新活动爆款每日限量供应
评论(没有评论)
验证码
【腾讯云】云服务器、云数据库、COS、CDN、短信等云产品特惠热卖中