oracle null排序,Oracle order by子句对NULL的排序

我们都知道在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 byzx@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 | DESCSpecify the ordering sequence (ascending or descending). ASC is the default.

NULLS FIRST | NULLS LASTSpecify 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值在排序结果的首部还是尾部。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值