3

What is wrong in below simple query? I tried to google it but not found

IF 1 = 1 THEN
  SELECT 1;
ELSE
  SELECT 12;
END IF;
5

I believe that syntax is actually valid; you can find similar statements in the MySQL documentation.

However, it's considered a control flow statement, and those are only allowed in stored programs in MySQL. You don't state that this is inside a stored program, so I'll assume it's not. If it is, please edit your question to provide more detail.

If you're trying to do this outside a stored program, see Evan Carroll's answer.

5

What you want is a CASE expression which is standard-SQL method of implementing a conditional and supported by every major database,

SELECT CASE WHEN 1 = 1 THEN 1 ELSE 12 END;

Or you can use the totally silly and proprietary IF statement

SELECT IF( 1=1, 1, 12 );
0
-1

This simple query can't be run outside the stored routines as stated by chapter 13.6.5 of the manual. For the single queries IF() function should be used instead. CASE may be a bit confusing because the CASE statement and the CASE operator has exactly the same syntax, inspite of completely different nature.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.