0
3

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 5 years have passed since last update.

【SQL】NULLを別の値に置き換える関数COALESCE関数

0
Posted at

文字列や数値を扱う際、NULLが混入しているカラム場合、NULLと文字列を結合するとNULLになり、NULLと任意の数値で四則演算を実行するとNULLとなる。

問題設定

purchase_id
character varying(255)
amount
integer
discount
integer
101 2960 [null]
102 7980 1000
103 1680 [null]

上のように、購入額とNULLを含む値引き額が格納されているデータ列から、値引き後の売り上げ金額を求める。

COALESCE関数

NULL値でない最初の引数を返す

COALESCE(a, b): aがNULLのときbを返す。aがNULLでないときaを返す。

SELECT
	a
	, COALESCE(a, 0)
FROM
	fic_table
;

実行結果

a COALESCE(a, 0)
1 1
[null] 0
[null] 0
2 2

aがNULLの箇所には0が、NULLでない個所では同じ値がそのまま入っている。

クエリ

SELECT
	purchase_id
	, amount
	, coupon
	, amount - discount AS dis_amount1
	, amount - COALESCE(coupon, 0) AS dis_amount1
FROM
	purchase_log_with_coupon
;

実行結果

purchase_id amount discount dis_amount1 dis_smount2
101 2960 [null] [null] 2960
102 7980 1000 6980 6980
103 1680 [null] [null] 1680
0
3
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
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?