Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL 'if exists' error

Tags:

mysql

exists

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?

like image 801
Cienz Avatar asked Mar 08 '26 07:03

Cienz


2 Answers

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;
like image 163
tom Avatar answered Mar 09 '26 21:03

tom


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
like image 23
bonCodigo Avatar answered Mar 09 '26 20:03

bonCodigo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!