Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL If statement with multiple conditions

Tags:

I want to write IF statement inside a Stored procedure in MySQL in the following way:

IF (exp1 and exp2 and exp3) or exp4 

I know MySQL will treat IF() as a function call. But I hope you got what I'm trying to achieve. I am new to MySQL syntax.

like image 521
avinash chavan Avatar asked Feb 22 '17 12:02

avinash chavan


People also ask

How do I write multiple if conditions in MySQL?

The syntax for the IF-THEN-ELSE statement in MySQL is: IF condition1 THEN {... statements to execute when condition1 is TRUE...} [ ELSEIF condition2 THEN {...

How do you write an if statement with multiple conditions?

When you combine each one of them with an IF statement, they read like this: AND – =IF(AND(Something is True, Something else is True), Value if True, Value if False) OR – =IF(OR(Something is True, Something else is True), Value if True, Value if False) NOT – =IF(NOT(Something is True), Value if True, Value if False)

Can we use nested if in MySQL?

As with other flow-control constructs, IF ... END IF blocks may be nested within other flow-control constructs, including other IF statements. Each IF must be terminated by its own END IF followed by a semicolon.


1 Answers

In a procedure the use of an IF is pretty straight forward:

IF (yourCondition [logical operator(OR, AND) another condition] ) THEN 

So in a practical example:

.... DECLARE m integer; DECLARE n integer; SET m = 1; SET n = 0; IF ((m>n AND m=1 AND n=0) OR m=n)THEN      some code here END IF; 

The evaluation of the conditions follows the parenthesis rule same as in a mathematical operation.

You can refer to the Docs

like image 109
Jorge Campos Avatar answered Oct 25 '22 13:10

Jorge Campos