VladutZzZ
VladutZzZ

Reputation: 720

Select * from table WHERE `column` = x if `column` != -1

I need to make a select like,

Select * from table WHERE column = x if column != -1

but i have no idea for now.

Anyone know or made in past something like that?

Thanks.

Upvotes: 1

Views: 862

Answers (1)

You should also write like this,

Select * from table 
WHERE 
1 = case when column != -1 then 
        case when column = x then 1 else 0 end
    else 1 end

You can utilize case when in where clause. Similarly you can add more conditional criteria like,

Select * from table 
WHERE 
1 = case when column != -1 then 
        case when column = x then 1 else 0 end
    else 1 end
AND 
1 = case when column1 [conditional operator] value then
        case when column1 = xx then 1 else 0 end
    else 1 end

This is just an example how you can integrate more conditional criteria together, even though you can add more case when in else part even.

Upvotes: 4

Related Questions