espresso_coffee
espresso_coffee

Reputation: 6110

How to apply if/else logic in where clause?

I have logic that is based on If/Else statement. This should be applied in SQL where clause filter. Here is example on how that should look like:

if (type = 'DEV') { // If type is DEV then status should be Y
   status = 'Y'
}else{ // If not do not apply filter
   1=1
}

I have tried this in SQL:

WHERE id IN (89,56,87)
   AND ( 
           (type = 'TRNG' AND status = 'Y') 
           OR 
           (1=1)
        )

I'm wondering if there is a way to achieve what I have in if/else statement?

Upvotes: 1

Views: 306

Answers (1)

GMB
GMB

Reputation: 222582

If I followed you correctly, you seem to be looking for :

WHERE id IN (89,56,87) AND ( type <> 'DEV' OR status = 'Y') 

This means : if type is 'DEV', then status must be equal to 'Y'. This implies that if type is different than DEV, then any value of status is allowed.

Upvotes: 7

Related Questions