oracle(二)-null總結

空值定義:

空值是無效的,未指定的,未知的或不可預知的值,空值不是空格或0。

1.包含空值的數學表達式的值都爲空值。

如:select name,12*sal+comm from emp; 其中comm爲獎金,可能爲null,導致整個表達式爲空

解決方案:用NVL函數:select name,12*sal+NVL(comm,0) from emp;                --當爲null的時候用0替代。

                                        select name,12*sal+NVL2(comm,comm,0) from emp;  --nvl2(a,b,c) 當a=null的時候,返回c;否則返回b

2.null永遠!=null

所有where語句中只能用  列名 is null   不能用 列名=null

3.count(expr)  返回expr不爲null的記錄總數,分組函數都有這個問題

使用nvl使分組函數無法忽略空值

select count(comm),count(nvl(comm,0)) from emp;  結果:3  14

4.如果集合中含有null,不能使用not in;但可以使用in;

這裏in後面有null,能返回數據;但加了not後,就不能返回數據了

如:select * from emp where deptno not in (10,20,null); -- 結果:沒有查到數據

原因:

id in (200,201,null)可以等價於id=200 or id=201or id=null

id not in (200,201,null)可以等價於id!=200 and id!=201 and id=null

第二種,因爲id=null相當於false,導致整個表達式爲false,無論傳何值都爲false,自然無法返回數據。

官方解釋:

in 等價於  = any

not in 等價於  != all 

5.null最大

降序排序的時候要注意這個問題,order by su.train_date desc nulls last

6.使用單行子查詢返回null

select * from emp where job = (select job from emp where ename = 'mike');

此時會找不到結果。好吧,這樣好像沒有啥問題,忽略這條。

7.插入時空字符串等價於null

在mysql數據庫中,常常會將字段都設置爲not null 用default 空字符串 來設置默認值,mysql會區分空字符串和null值。會將空字符串視爲有值對象,所以此操作沒有問題。

但是在切換成oracle中,需要跟緊業務需要,來對每個字段進行是否爲null的設置。oracle中,會將空字符串視爲null值,如果該字段是not null,寫入空字符的時候會報錯。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章