kusanagi
kusanagi

Reputation: 14614

mysql ifnull where

i need such query

select * from t where
field=ifnull(:param, field) 'it not work's

so if param=NULL i have

select * from t where field is NULL

but if param =4 i have

select * from t where field=4

Upvotes: 0

Views: 4054

Answers (4)

Harish
Harish

Reputation: 2324

You can try this alternative this might help you

 select * from t where (field = NULL AND param= NULL) OR field ='4'

Upvotes: 1

Jahan Zinedine
Jahan Zinedine

Reputation: 14874

You can use the case when in where clause AFAIK bot not sure about MySQl,

But the better approach is to translate them,

you can read about that SQL WHERE clauses: Avoid CASE, use Boolean logic

So

select * from t where (:param is null and filed is null) or (filed = :param)

Upvotes: 3

Sachin Shanbhag
Sachin Shanbhag

Reputation: 55489

I think you are looking for NULLIF instead of ifnull

I think better approach would be to use CASE in where clause in your case.

Upvotes: 0

Elzo Valugi
Elzo Valugi

Reputation: 27866

When working with NULL you cannot use arithmetic operators. Try COALESCE to make a logical if with values integer or NULL

mysql> SELECT COALESCE(NULL,1);
    -> 1
mysql> SELECT COALESCE(NULL,NULL,NULL);
    -> NULL

Upvotes: 0

Related Questions