[ Oracle ] Case ~ When ~ Then で null 判定 ( is not null )

Pocket

Oracle データベースでは、SQL 内で if 文のような分岐を行う場合には Case ~ When ~ Then を使用することができますが、以下のような記述で null の判定を行うことはできません。

スポンサーリンク

間違った null 判定

例えば、レコードが1件も存在しないテーブルに対して、以下の SQL を実行すると 出力としては ‘null’ を期待してしまいますが、結果は ‘not null’ となります。下記のサンプル SQL は間違った null 判定方法です。

select 
   case max(col1)
     when null then 'null'
     else           'not null'
   end 
from 
   table1

// 出力結果
not null

期待する null 判定を行うには

case ~ when で null 判定を行うには、以下のように when 句で null 判定を行う必要があります ( is null または is not null を使用します ) 。

select 
   case 
     when max(col1) is null then 'null'
     else                        'not null'
   end 
from 
   table1

// 出力結果
null
スポンサーリンク


Pocket

Leave a Comment

Your email address will not be published. Required fields are marked *