LoginSignup
0
1

More than 3 years have passed since last update.

【PostgreSQL】NULL/空白以外のデータを探したいとき

Last updated at Posted at 2020-05-04

前提

  • DB は PostgreSQL

テーブル構成

  • たとえば、以下のようなテーブルがある。
  • test_name に文字列が入っているはず。たぶん。
  • sts_flg = 1 のデータが有効データ。
test=# \d m_test
               |                            |                               修飾語                               
-----------------+-----------------------------+-------------------------------------------------------------
 test_no         | integer                     | not null default nextval('m_test_test_no_seq'::class)
 test_name       | character varying(250)      | 
 sts_flg         | smallint                    | default 1
インデックス:
    "m_test_pkey" PRIMARY KEY, btree (test_no)

やいたいこと

  • 上記テーブル構成の中から、test_nameの入っているデータの数がしりたい。
  • 空白やNULLは知りたくない。

現在のデータが何件あるか検索してみよ

  • 全体は110件ある。ふむふむ
test=# SELECT COUNT(*) FROM m_test WHERE sts_flg = 1;
 count 
-------
   110
(1 )

NULLと空白以外を抽出する SQL を準備する

  • coalesce を使用して、NULL/空白ではない文字列を抽出する。
  • coalescetest_name があるときは、1をかえし、それ以外は 0 を返す。
SELECT COUNT(*) 
FROM m_test
WHERE sts_flg = 1 
AND (CASE 
        coalesce(test_name, '') WHEN '' THEN 0
        ELSE 1
        END
) <> 0;

実行してみる

  • やったー!うごいた!100件が空白じゃない。そして残り10件はNULL/空白なのね
test=# SELECT COUNT(*)  
test-# FROM m_test
test-# WHERE sts_flg = 1 
test-# AND (CASE 
test(#         coalesce(test_name, '') WHEN '' THEN 0
test(#         ELSE 1
test(#         END
test(# ) <> 0;
 count 
-------
   100
(1 )
0
1
2

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