mariadb IF statements error message?

Mr.Park picture Mr.Park · Jan 27, 2018 · Viewed 7.2k times · Source

I test sql querys.

    IF 3 = 3 THEN 
       SELECT 'TRUE'
    ELSE
       SELECT 'FALSE'
    END IF;

I excuted that query on SQLyog.

I got the error message below.

 You have an error in your SQL syntax; check the manual that corresponds to 
 your MariaDB server version for the right syntax to use near 'ELSE SELECT 
 'FALSE' END IF' at line 3

That query is very simple. I don't know why happen error message.

Answer

elenst picture elenst · Jan 28, 2018

IF itself is not a query, it cannot be executed as a standalone statement.

There are two different IFs that you can use.

One is the conditional construct in compound statements. It can be used in stored routines:

DELIMITER $
CREATE PROCEDURE pr()
BEGIN
    IF 3 = 3 THEN 
       SELECT 'TRUE';
    ELSE
       SELECT 'FALSE';
    END IF;
END $
DELIMITER ;
CALL pr;

Or, if you are running a reasonably new version of MariaDB (10.1+), you can also use it in an anonymous block:

DELIMITER $
BEGIN NOT ATOMIC
    IF 3 = 3 THEN 
       SELECT 'TRUE';
    ELSE
       SELECT 'FALSE';
    END IF;
END $
DELIMITER ;

Another is the IF function, which can be used inside a query:

SELECT IF(3 = 3 THEN 'TRUE','FALSE');