在寫sql的時候,經常會遇到和null相關的問題,經常用到慮空函數。常見的有NVL,NULLIF,COALESCE函數,其他還有很多在此不介紹了。
- 1.NVL-----
NVL
lets you replace null (returned as a blank) with a string in the results of a query. Ifexpr1
is null, thenNVL
returnsexpr2
. Ifexpr1
is not null, thenNVL
returnsexpr1
.
- 2.NULLIF------
NULLIF
comparesexpr1
andexpr2
. If they are equal, then the function returns null. If they are not equal, then the function returnsexpr1
. You cannot specify the literalNULL
forexpr1
. - 類似於:CASE WHEN expr1 = expr 2 THEN NULL ELSE expr1 END
- 3.
COALESCE-----COALESCE
returns the first non-nullexpr
in the expression list. At least oneexpr
must not be the literalNULL
. If all occurrences ofexpr
evaluate to null, then the function returns null. - 類似於:CASE WHEN expr1 IS NOT NULL THEN expr1 ELSE expr2 END
- COALESCE (expr1, expr2, ..., exprn), for n>=3 類似於:CASE WHEN expr1 IS NOT NULL THEN expr1 ELSE COALESCE (expr2, ..., exprn) END
總結一下:
nvl,表達式1 爲空,就返回表達式2。
nullif,表達式 1和表達式2如果相等,返回null,不相等返回表達式1.
coalesce,返回表達式不爲空項結束。例子:coalesce(手機號,電話,郵箱) as '聯繫方式'
搬運工來自:SQL Functions