Oracleorderby子句对NULL的排序

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

蒙城ssl适用于网站、小程序/APP、API接口等需要进行数据传输应用场景,ssl证书未来市场广阔!成为创新互联的ssl证书销售渠道,可以享受市场价格4-6折优惠!如果有意向欢迎电话联系或者加微信:18980820575(备注:SSL证书合作)期待与您的合作!

下面做一组实验观察一下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值在排序结果的首部还是尾部。

本文名称:Oracleorderby子句对NULL的排序
当前路径:https://www.cdcxhl.com/article42/gpihhc.html

成都网站建设公司_创新互联,为您提供App设计服务器托管用户体验静态网站Google关键词优化

广告

声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联

成都app开发公司