有没有一种方法可以设置Oracle默认使用NULL LAST(或NULL FIRST)的排序方式,而不必在每个查询中都加上它?
不,无法更改 NULLS FIRST
和 NULLS LAST
的默认行为:
升序排序的默认值为 NULLS LAST,降序排序的默认值为 NULLS FIRST。
我不能证明它是不可能更改的,但是在最有可能实施该功能的地方,我找不到这样的功能。
SQL 选项 手册 中未提及任何内容。
参数 V$PARAMETER
中的任何 nls 参数都不能控制它:select * from v$parameter where name like '%nls%';
隐藏参数 没有 隐藏参数。 我尝试搜索类似于 %null% 或 %sort% 的任何内容,但它们都与相关性没关系。
Locale Builder Oracle 允许您创建自己的自定义排序。 它有很多选项,但是没有一种选项允许您定义如何对 NULL 进行排序。 将 Major Sort 和 Minor Sort 数字设置得非常高或低不会改变它(我希望 NULL 是作为硬编码的小值或大值实现的)。 您可以设置 0x0000 的排序顺序,它是“NULL”,但那是一种不同类型的 NULL。
升序排序
SQL> with t1(col) as(
2 select 1 from dual union all
3 select 2 from dual union all
4 select null from dual union all
5 select 3 from dual
6 )
7 select *
8 from t1
9 order by col asc nulls last
10 ;
结果:
COL
------
1
2
3
null
降序排列
SQL> with t1(col) as(
2 select 1 from dual union all
3 select 2 from dual union all
4 select null from dual union all
5 select 3 from dual
6 )
7 select *
8 from t1
9 order by col desc nulls last
10 ;
结果:
COL
----------
3
2
1
null
ORDER BY EMPLOYER_NAME DESC NULLS LAST
我很惊讶还没有人提到,但是你可以使用COALESCE
函数,它从参数中获取第一个非空值。在大多数数据库管理系统中都可用:
SELECT [Name], [Email] FROM Users
ORDER BY COALESCE([Name], 'zzz')
null
,则函数将返回 'zzz' 将记录向下推。在大多数情况下,它都能发挥作用。文档在此处。ORDER BY Name NULLS LAST
更好吗? - rascio我们可以使用类似于.. Order by col1 desc nulls last, col2 desc的方式。我们也可以使用COALESCE,但是如果我们有不同数据类型的列,比如一个是日期,另一个是数字,它就不会有帮助。