MySQL If statement with multiple conditions?



You can use if statement in a stored procedure with multiple conditions with the help of AND or OR operator. The syntax is as follows −

DECLARE X int; DECLARE Y int; SET X = value1; SET Y = value2; IF ( (X < Y AND X > value1 AND Y >value2) OR X! = anyValueToCompare) THEN    yourStatement; ELSE    yourStatement; END IF

Now to understand the above syntax, let us create a stored procedure. The query to create a stored procedure is as follows −

mysql> create procedure SP_IFELSEDEMO()    -> BEGIN    -> DECLARE X int;    -> DECLARE Y int;    -> SET X=100;    -> SET Y=400;    -> IF ( (X < Y AND X > 99 AND Y >300) OR X! = 10 ) THEN    ->    SELECT 'Logic is Correct';    -> ELSE    ->    SELECT 'Logic is not Correct';    -> END IF;    -> END;    -> // Query OK, 0 rows affected (0.27 sec) mysql> DELIMITER ;

Now call the stored procedure with the help of the CALL command. The query is as follows −

mysql> call SP_IF ELSEDEMO();

Output

+------------------+ | Logic is Correct | +------------------+ | Logic is Correct | +------------------+ 1 row in set (0.04 sec) Query OK, 0 rows affected (0.07 sec)
Updated on: 2019-07-30T22:30:25+05:30

8K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements