HiveBrain v1.2.0
Get Started
← Back to all entries
snippetsqlMinor

How do I write a conditional statement (IF) with MySQL?

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
statementwithconditionalwritemysqlhow

Problem

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;

Solution

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 );

Code Snippets

SELECT CASE WHEN 1 = 1 THEN 1 ELSE 12 END;
SELECT IF( 1=1, 1, 12 );

Context

StackExchange Database Administrators Q#214030, answer score: 5

Revisions (0)

No revisions yet.