In MySQL I would like to compare a user-defined variable via an IF-THEN statement:
SET @num = 10;
IF @num > 7 then
select * from person;
ELSE
select name from person;
END IF;
How could I do that?
Currently I get an error near the IF @num > 7.
3
Answers
You cannot use If-then statement directly in a SELECT query.
But you can use a conditional operator like this :
If you want to add logical operators like IF-THEN statements in your queries, use stored procedures:
Compound statements like IF/THEN/ELSE are only supported in MySQL’s stored routine language.
This is from the manual:
Typically if you need to run SQL queries conditionally and you aren’t using stored routines, you would put the conditional logic into some client application programming language, e.g. Java, Python, Go, PHP, or whatever is your favorite language.
From its earliest days, SQL was intended to be used in combination with other programming languages.
If you really can’t write the code in a client application, here’s a workaround that can work for instance to run your example in an SQL script:
If you have more complex conditional code, this workaround might not be practical.