在使用 PostgreSql
時,實際場景中會出現某個字段為空或空字符串,就取另外一個字段或給默認值,在Oracle
數據庫中用函數NVL
就行實現,那么在PostgreSql
可以使用COALESCE
函數,與Oracle
的NVL
一樣接收兩個參數。區別在於NVL
函數的第一個參數對NULL
與空字符串,都識別為空,而COALESCE
只識別NULL
。
比如下面數據的order_code
字段是NULL
,cus_name
字段是空字符串:
使用函數COALESCE
設置NULL
與空字符串的默認值,看下對空字符串是否生效。
select
coalesce(cus_name, 'AA') as cus_name,
coalesce(order_code, 'S01') as order_code
from
t_order;
從結果可以看出,cus_name
字段為空字符串,結果還是空字符串,order_code
字段為NULL
,結果設置了默認值。那么是否可以將cus_name
的空字符串也設置成功默認值呢?這里可以使用case when
語句。
select
(case
when cus_name is null
or cus_name = '' then 'AA'
else cus_name
end) as cus_name,
coalesce(order_code, 'S01') as order_code
from
t_order;
從結果上看已經實現我們想要的效果,但是使用case when
來處理空字符串,從SQL
語句簡潔來看不太舒服,可以參考如下寫法:
select
coalesce(nullif(cus_name,''),'AA') as cus_name,
coalesce(order_code, 'S01') as order_code
from
t_order;
這里使用到了NULLIF
函數,意思是第一個參數與第二個參數一致,就返回NULL
。
結果與使用case when
效果一樣,從SQL
的簡潔來看,個人更偏向第二種來判空。