3
2

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のin句でテーブル検索結果がNULLの時は全件、それ以外は絞り込み結果を返す

Posted at

昔調べて書いてあるサイトを見つけたきがするけど、見つからないのでメモ書き

select
	*
from TestTable
where key in (select key from TestTable where col1 > 100)

この形式で複数件をINできる・・・んだけど、件数0件のときはNULLでIN検索するため0件検索される。

0件のとき全件検索をしたい場合は

select
	*
from TestTable1
where 1 = case when (select count(key) from TestTable where col1 > 100) = 0 then 1 
               when key in (select key from TestTable where col1 > 100) then 1 
               else 0 end

つまり、0件なら問答無用で正しい条件、1件以上あればデータがあるときのみ正しい条件となるようにCase式でWhere条件を記載する

もうちょっとスマートなやり方もありそうだけど・・・

3
2
6

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
3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?