Skip to content
Advertisement

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.

Advertisement

Answer

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);
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement