dnlopezm
dnlopezm

Reputation: 33

CASE in WHERE expression using IN clause

I need that when var1 is equal to 'Y' the query show the result of the table with the column = 'Y', but when var1 = 'N' the result should be the data with column with 'Y' and 'N'. I need to put it in a where clause, cause I'm using oracle forms. I tried this way but the query didn't show any result:

SELECT  *
FROM    table
WHERE   column1 IN ((CASE WHEN var1 = 'Y' THEN q'[('Y')]'
                                  ELSE TO_CHAR(q'[('Y','N')]')
                                  END))

Can you help me? Thank you.

Upvotes: 3

Views: 310

Answers (1)

Michael Berkowski
Michael Berkowski

Reputation: 270599

There is no need for CASE logic here, as you can fit this into a regular WHERE clause with boolean logic, wrapping each condition (var1 = 'Y', var1 <> 'Y') in a () group.

SELECT *
FROM table
WHERE
  (var1 = 'Y' AND column1 = 'Y')
  OR (var1 <> 'Y' AND column1 IN ('Y','N'))

Note, I used var1 <> 'Y' here to emulate your ELSE case, but if it is only two possible values Y/N you may use var1 = 'N' for clarity.

WHERE
  (var1 = 'Y' AND column1 = 'Y')
  OR (var1 = 'N' AND column1 IN ('Y','N'))

Actually, if Y/N are the only possible values for column1, then it could be simplified to:

WHERE
  (var1 = 'Y' AND column1 = 'Y')
  -- Returns all rows for column1 if Y,N are the only possible values
  -- No need to explicitly filter it
  OR (var1 <> 'Y')

Upvotes: 2

Related Questions