oracle字段为null

create table test_null (
     id integer primary key, 
     status varchar2(5), 
     no number);

insert into test_null values (1,’Y',1);

insert into test_null values (2,’N',2);

insert into test_null values (3,null,null);

commit;



SQL 一> select * from test_null;

ID STATUS             NO
———- ———- ———-
1 Y                   1

2 N                   2

3

SQL 二> select * from test_null where status = ‘Y’;

ID STATUS             NO
———- ———- ———-
1 Y                   1

SQL 三> select * from test_null where status != ‘Y’;

ID STATUS             NO
———- ———- ———-
2 N                   2

    test_null表格里面有3条记录,其中有一条记录status是null;

    但是SQL中无论是选择status = ‘Y’ 还是status != ‘Y’,都不会返回这条记录;

SQL> select count(*) from test_null where status != ‘Y’;

COUNT(*)
———-
1

SQL> select * from test_null where status is null;

ID STATUS             NO
———- ———- ———-
3

   这里可以看到,对应null的行,只有用status is null这样的条件是,才会返回这条记录;

   所以,如果这个字段可以是null,并且要包含null的情况的话,

   在oracle中,必须用nvl这样一个函数来,nvl(status,’N’)的意思是如果这个字段是null,就用’N’来代替,如果不是null,就用本来的值;

SQL> select * from test_null where nvl(status,’N') != ‘Y’;

ID STATUS             NO
———- ———- ———-
2 N                   2

3

   所以,在设计数据库的时候,应该尽可能的将这列加上not null限制,避免应用中出现意外的错误;

猜你喜欢

转载自mlxnle.iteye.com/blog/1423443