加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Oracle order by子句对NULL的排序

发布时间:2020-12-12 15:27:20 所属栏目:百科 来源:网络整理
导读:我们都知道在Oracle SQL语句中order by 是用来排序查询出来的结果集的,而在Oracle中NULL值是一个很特殊的值,如果order by指定的列有NULL值,那排序结果又是怎样的呢。 下面做一组实验观察一下order by时Oracle是怎么处理NULL的 版本11.2.0.4 1、创建测试表

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

下面做一组实验观察一下order by时Oracle是怎么处理NULL的

版本11.2.0.4

1、创建测试表并插入测试数据

zx@ORCL>createtablet(idnumber,namevarchar2(10));

Tablecreated.

zx@ORCL>insertintotvalues(1,'zx');

1rowcreated.

zx@ORCL>insertintotvalues(2,'wl');

1rowcreated.

zx@ORCL>insertintotvalues(3,'zxt');

1rowcreated.

zx@ORCL>insertintotvalues(4,NULL);

1rowcreated.

zx@ORCL>insertintotvalues(5,'yhz');

1rowcreated.

zx@ORCL>insertintotvalues(6,NULL);

1rowcreated.

zx@ORCL>commit;

Commitcomplete.

zx@ORCL>select*fromt;

	IDNAME
----------------------------------------
	1zx
	2wl
	3zxt
	4
	5yhz
	6

6rowsselected.

2、测试order by

zx@ORCL>select*fromtorderbynameasc;

	IDNAME
----------------------------------------
	2wl
	5yhz
	1zx
	3zxt
	6
	4

6rowsselected.

zx@ORCL>select*fromtorderbynamedesc;

	IDNAME
----------------------------------------
	4
	6
	3zxt
	1zx
	5yhz
	2wl

6rowsselected.

看到不同的排序方式,NULL值所排序的位置不同。升序(asc)NULL排在最后,降序(desc)NULL排在最前。

我们再来看看官方文档是怎么描述的

ASC | DESCSpecify the ordering sequence (ascending or descending).ASCis the default.

NULLS FIRST | NULLS LASTSpecify whether returned rows containing nulls should appear first or last in the ordering sequence.

NULLSLASTis the default for ascending order,andFIRSTis the default for descending order.

可以看到我们的实验结果与官方文档描述是一致的。而且还可以使用NULLS FIRST|NULLS LAST来决定NULL的值是排在最前还是排在最后。

3、再次做实验验证

zx@ORCL>select*fromtorderbynameascnullsfirst;

	IDNAME
----------------------------------------
	6
	4
	2wl
	5yhz
	1zx
	3zxt

6rowsselected.

zx@ORCL>select*fromtorderbynameascnullslast;

	IDNAME
----------------------------------------
	2wl
	5yhz
	1zx
	3zxt
	6
	4

6rowsselected.

zx@ORCL>select*fromtorderbynamedescnullsfirst;

	IDNAME
----------------------------------------
	4
	6
	3zxt
	1zx
	5yhz
	2wl

6rowsselected.

zx@ORCL>select*fromtorderbynamedescnullslast;

	IDNAME
----------------------------------------
	3zxt
	1zx
	5yhz
	2wl
	6
	4

6rowsselected.

从结果可以看出使用NULLS FIRST|NULLS LAST可以直接控制NULL值在排序结果的首部还是尾部。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读