代码改变世界

oracle 中null 的处理

2013-11-13 14:15  明镜亦非台  阅读(1194)  评论(0编辑  收藏  举报

  null表示不确定,未知的意思,在oracle中是不能使用“=”来进行条件查询的,null不等于任何人或者null,判断是否为null只能使用 “is null” or “is not null” ,其他条件查询结果都为UNKNOWN值。

  与false区别:条件判断unknown值与false看起来挺像,他们哥俩还是有区别的,not unknown为unknown,但是not false为true。

  运算:null与任何人进行运算(+、-、*、/、),都是null。

     但是连接符与null则不同:select null||'xiaoer', ''||'xiaoer' from dual;

  排序:如果有null值,则默认排序是放在最后的,若想排在前面则:select comm from emp order by comm nullls first;-- or nulls last;

  null值在普通函数中使用:NVL,CONCAT,REPLACE函数中有null作为参数,可以正常使用:

          select concat(null,'abc'),null||'abc' from dual;

          select replace('abc',null,'abcd') from dual;
          select replace('abc','ab',null) from dual;
          select nvl(null,'a') from dual;

    注意:两者类型一致:

                          select ename,nvl(comm, 0) from emp;
                          select ename,nvl(comm, '零') from emp; 

    但是在decode函数中oracle默认是null=null的,注意地方。

               select ename,decode(comm,null,0,comm) joba from emp;

    在case...when...else 中是is null来判断的。

    组合函数中,忽略null值,所以组合函数中需要进行转换:

                    select count(comm) from emp; -- [将null归类为同样的一栏,故结果为count(not null + 1)]---》

                              改:------select count(nvl(comm,0)) from emp;  ----这个可以有!
                    select avg(comm) from emp;--[将null归类为同样的一栏,故结果为sum(*)/(not null + 1)]

    子查询中null:

 ---select ename,comm from emp where comm in (select comm from emp where ename='ALLEN' or ename='SCOTT');

                                ------把null的排除。

   ----select ename,comm from emp where comm not in (select comm from emp where ename='ALLEN' or ename='SCOTT');--无

----摘:

在oracle里,如果是空字符串,oracle会把它当做null来对待,但‘’和null是不相等的。
•‘’只能表示空字符串,null可以 表示任何类型。
•Oracle10.2,11.2官方描述:
Oracle Database currently treats a character value with a length of zero as null. However, this may not continue to be true in future releases, and Oracle recommends that you do not treat empty strings the same as nulls.
Do not use null to represent a value of zero, because they are not equivalent.

组合约束中null: 

  组合约束中,只要有一列是非null值,那么null=null。