在Oracle中使用null,''(空字符串),'_'(空格)時,有沒有遇到問題?產生疑惑?
1、NULL和''(空字符串)是一個意思
注:為了便於區分空字符串和空格,下面的示例均以'_'代表空格。
舉個例子:
1 --建表 2 create table tbl_a (col_a varchar2(1), col_b int); 3 4 -- 造數據 5 insert into tbl_a values(‘_’, 1); -- 插入空格 6 insert into tbl_a values(‘’, 2); -- 插入空字符串 7 insert into tbl_a values(null, 3); -- 插入NULL
以上SQL執行成功后,執行select來檢查:
1 select count(*) from tbl_a; -- 結果是 3 2 select count(*) from tbl_a where col_a = ‘_’; -- 結果是 1 3 select count(*) from tbl_a where col_a = ‘’; -- 結果是 0 4 select count(*) from tbl_a where col_a is null; -- 結果是 2
注意:由於''(空字符串)默認被轉換成了NULL,不能使用 = ''作為查詢條件。也不能用 is ''。雖然不會有語法錯誤,但是不會有結果集返回。只能用is null,不等於就是 is not null。
進一步驗證:
select nvl(col_a, ‘a’) from tbl_a;
結果:
原來,在Oracle中,null和''(空字符串)是一個意思。
2、分析函數與NULL
在使用AVG,MAX,SUM,COUNT等函數時,為NULL的記錄會被忽略。
再插入幾條數據:
1 insert into tbl_a values(null, null); -- 插入NULL 2 -- 執行成功。 3 -- 再次證明,’’ 被當作了null處理. 4 -- 因為該字段是 int 類型,如果是字符串,執行會報錯 5 insert into tbl_a values(‘a’, ‘’);
查看數據:
select * from tbl_a;
結果如下:
注:_代表空格,其余空白處表示NULL
驗證:
1 select AVG(col_b) from tbl_a; -- 結果為 2 ,NULL的紀錄行忽略掉了 2 select MAX(col_b) from tbl_a; -- 結果為 3 3 select SUM(col_b) from tbl_a; -- 結果為 6 4 select COUNT(col_b) from tbl_a; -- 結果為 3 5 select COUNT(col_a) from tbl_a; -- 結果為 2 6 select COUNT(*) from tbl_a; -- 結果為 5
3、排序時,NULL作為無窮大處理
例:
select * from tbl_a order by col_b desc ;
結果如下: