# MySQL ifnull vs coalesce 比較 ###### tags: `資料庫` `MySQL` `MSSQL` 2021/10/05 ::: info 結論: 看要用在哪邊, 如果需要從多個欄位中取得第一個非NULL的用coalesce, 可以省下很多 if 判斷; 如果只要比對單一欄位的話就隨意吧~ ::: 從參考資料得知: - ISNULL 執行時間比 COALESCE 高出10%左右,理論COALESCE效能比較好 - COALESCE 是標準SQL,ISNULL 不保證每個DB都能使用 但有個大問題,我參考的這些文章超級久了, 效能放在現今應該有很大的改善了 因此參考就好, 有空我也來個比較XD 我覺得實際看要用在哪邊 如果需要從多個欄位中取得第一個非NULL的用coalesce, 可以省下很多 if 判斷 如果只要比對單一欄位的話就隨意吧~ 另外, 若有需要排除空白的話,請善用NULLIF(\`欄位\`, '') 使用範例: ```SQL SELECT coalesce(NULL, `欄位1`, `欄位2`, ...(略)... , '預設值'); -- 如果遇到欄位可能是空白的話,善用NULLIF SELECT coalesce(NULLIF(`欄位1`, ''), NULLIF(`欄位2`, '')); SELECT ISNULL(`欄位1`, `預設值`); ``` --- 參考文章 2011/01/20 mysql, ifnull vs coalesce, which is faster? https://stackoverflow.com/questions/4747877/mysql-ifnull-vs-coalesce-which-is-faster >自 1992 年以來 COALESCE 一直是標準 SQL 的一部分 2004/11/30 Performance: ISNULL vs. COALESCE http://dataeducation.com/performance-isnull-vs-coalesce/ 範例語法是MSSQL >I ran these tests several times on a few different servers, and ISNULL appears to pretty consistently out-perform COALESCE by an average of 10 or 12 percent. But that’s the difference between 6 seconds and 5.3 seconds (the approximate average runtimes per test on my servers), over the course of a million exections. Hardly worth the functionality and standards compliance sacrifice, at least in the scenarios I use these functions for.