0
1

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.

ISNULLが効いていない(ように見える)場合

Last updated at Posted at 2019-11-28

ISNULLでNullを別の値に置き換えることができるが、以下のような場合置き換えることができずUI上Nullが返ってきているように見える。

SELECT
  ISNULL(COUNT(column2), 0)
FROM
  table1
WHERE
  column1 = 'xxx'
GROUP BY
  column1
;

column1が'xxx'のレコードが存在しない場合は「0」という結果を期待するが、実際に返ってくるのはNullで、ISNULLが効いていないように見える。
実際はCOUNT(column2)がNullを返しているのではなくSELECTの結果自体が0件なので、ISNULLを実施する行がそもそも存在しない。
以下のSQLの方がイメージしやすい。

SELECT
  ISNULL(column1, 'aaa')
FROM
  table1
WHERE
  1 = 2
;

結果は0件なので、当然ISNULLを実施するcolumn1も存在しないので結果はNullとなる。

どうしてもCOUNTの結果がNullの場合に0と出力したい場合は

SELECT
  ISNULL(
    (SELECT
       COUNT(column2)
     FROM
       table1
     WHERE
       column1 = 'xxx'
     GROUP BY
       column1), 0)
;

0
1
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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?