3

I got a error in my MySQL query:

if not exists(select * from tb_user where user_id=1) then
     select 'ok' as rul;
else
     select 'not' as rul;
end if;

Where's my problem?

Michael Petrotta
  • 59,888
  • 27
  • 145
  • 179
Cienz
  • 33
  • 1
  • 4
  • You may also want to check on this [performance of count(*) vs exisits post](http://stackoverflow.com/questions/5264658/is-exists-more-efficient-than-count0) to embark in the best solution for you. :) – bonCodigo Dec 21 '12 at 07:49

3 Answers3

4

The IF statement can only be used in stored functions. You can do what you want with the IF() function, as follows:

SELECT IF(EXISTS(select * from tb_user where user_id=1), 'ok', 'not') as rul;
tom
  • 18,953
  • 4
  • 35
  • 35
3

Another method: You may also use case when

Select case
when exists(select * from tb_user where user_id=1)
then 'Ok'
else 'Not'
end
;

* SQLFiddle Demo

Sample table:

ID  NAME
1   john
2   tim
3   jack
4   rose

Query: renamed the columns as Status

Select case
when exists(select * from table1 where id=1)
then 'Ok'
else 'Not'
end as Status
;

Results:

STATUS
Ok
bonCodigo
  • 14,268
  • 1
  • 48
  • 91
1
SELECT IF(COUNT(*) > 0, 'ok', 'not') rul FROM tb_user WHERE user_id = 1;
Devart
  • 119,203
  • 23
  • 166
  • 186