0

I would like to SELECT WHERE column IS NULL or =value depending on result of subquery.

Here is an example incorrect solution that demonstrates the problem:

SELECT *
FROM table
WHERE column=(
  SELECT (CASE WHEN COUNT(*) = COUNT(COLUMN) THEN MIN(column) END)
  FROM table
)

When the subquery returns NULL the other query will return nothing because column=NULL is never true. How do I fix this?

(Subquery source: https://stackoverflow.com/a/51341498/7810882)

D-Shih
  • 44,943
  • 6
  • 31
  • 51
user7810882
  • 223
  • 1
  • 4
  • 14

2 Answers2

1

From your question. just add OR column IS NULL in where clause.

You will get the subquery condition or column IS NULL data.

SELECT *
FROM table
WHERE column= (
  SELECT (CASE WHEN COUNT(*) = COUNT(COLUMN) THEN MIN(column) END)
  FROM table
) OR column IS NULL
D-Shih
  • 44,943
  • 6
  • 31
  • 51
1

If you are only looking for one row, I would suggest:

select t.*
from table t
order by column nulls first
fetch first 1 row only;
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786