Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL syntax for "if exists"

Why I'm getting this error:

#1064 - You have an error in your SQL syntax;  
check the manual that corresponds to your MySQL server version 
for the right syntax to use near 
'IF EXISTS(SELECT id FROM mytable WHERE id = '1')' at line 1 

My SQL query:

IF EXISTS(SELECT id FROM mytable WHERE id = '1')

Thanks.

like image 979
lolalola Avatar asked Feb 27 '23 16:02

lolalola


1 Answers

IF EXISTS only works in a stored procedure. Outside of a stored procedure, IF() is a function which takes 3 arguments. Proper usage would be

SELECT IF(EXISTS(SELECT `column` FROM `table` WHERE `id` = `1`), 1, 0);
like image 163
Siqi Lin Avatar answered Mar 07 '23 14:03

Siqi Lin