Reputation: 911
I am trying to determine whether id is present or not in my MySQL table. If not I need to return -1 instead. So I tried IFNULL
. However I am still getting empty.
select ifnull(id, -1) as id from docs where id=3909090 LIMIT 1
I am supposed to get -1 here. Any suggestions?
Upvotes: 0
Views: 82
Reputation: 147146
You can COUNT
the number of rows with id = 3909090
and if 0, return -1
, otherwise the id
value:
select case when count(*) = 0 then -1
else min(id)
end as id
from docs
where id = 3909090
Note we use min(id)
to avoid issues with grouping.
Upvotes: 1
Reputation: 5459
You can use IFNULL()
this way
SELECT IFNULL( (select id from docs where id=3909090 LIMIT 1) ,-1) AS ID;
Upvotes: 3
Reputation: 882
You can use NOT EXISTS
for this.
select -1 as id from docs where NOT EXISTS (SELECT * FROM docs WHERE id=3909090 )
NOT EXISTS
will return True if a record is not found in the table with that id. Since WHERE
condition is true it will print outer query value which is -1.
Upvotes: 1