Oracle order by子句对NULL的排序
2017-01-12 15:07
357 查看
我们都知道在Oracle SQL语句中order by 是用来排序查询出来的结果集的,而在Oracle中NULL值是一个很特殊的值,如果order by指定的列有NULL值,那排序结果又是怎样的呢。
下面做一组实验观察一下order by时Oracle是怎么处理NULL的
版本11.2.0.4
1、创建测试表并插入测试数据
我们再来看看官方文档是怎么描述的
ASC | DESC Specify the ordering sequence (ascending or descending).
3、再次做实验验证
下面做一组实验观察一下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).
ASCis the default.NULLS FIRST | NULLS LAST Specify whether returned rows containing nulls should appear first or last in the ordering sequence.
NULLS
LASTis the default for ascending order, and
NULLS
FIRSTis 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值在排序结果的首部还是尾部。
相关文章推荐
- JVM虚拟机内存及垃圾收集
- 使用C++实现JNI接口需要注意的事项
- 基于 Red Hat 的发行版 Oracle Linux 正式发布Oracle Linux 7.1
- Oracle Containers for J2EE远程安全漏洞(CVE-2014-0413)
- Oracle 10g R2不能使用EM的问题
- 表空间操作
- PreparedStatement中in子句的处理
- VMware下RedHat4.8_64位安装Oracle 10g RAC--简略脚本
- oracle sql日期比较
- 基于 Red Hat 的发行版 Oracle Linux 正式发布Oracle Linux 7.1
- OS block size和Oracle block size,查找OS Blocksize的方法
- oracle中创建数据库和表空间的几点总结
- 数据库自动备份脚本
- oracle的nvl函数的使用介绍
- 解决oracle用户连接失败的解决方法
- oracle的一些tips技巧
- Oracle 下的开发日积月累
- Oracle存储过程之数据库中获取数据实例