0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

COALESCEでnullを任意の値で返す

Posted at

COALESCEの使用場面

nullの値がある場合、代わりの任意の値で出力したい場面があると思います。
このような場合、COALESCEという関数があることを知りました。
今回は業務の中で、null値を0で出力する必要がありましたので備忘録として残します。

null値を含むデータを用意

今回はcustomersテーブルを用意し、以下のカラムを設定しました。
・id(自動連番)
・name
・phone1
・phone2

それぞれ、phone1とphone2にnull値を用意しています。
これらを任意の値(今回は0)で出力します。

select * from customers;

スクリーンショット 2021-11-30 17.54.14.png

select id,name,coalesce(phone1, 0) as phone1,coalesce(phone2, 0) as phone2 from customers;

スクリーンショット 2021-12-01 9.02.26.png

画像の通り、null値を0で出力することができます。
実務では他にも、null値を"不明"として集計するなどに活用でそうです。上記の例でしたら、customersテーブルのnameカラムがnullの場合、'不明'と出力する等々などです。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?