MySQL: IF-THEN-ELSE Statement

Profile picture for user arilio666

The IF-THEN-ELSE Statement in MySQL does pretty much what a conditional statement does in any other language here we will be using the stored procedure to give in the task.
As we all know that a stored procedure is a pre-compiled stored language ready for execution with its stored table within.

Now we won't be discussing much in-depth about the PROCEDURE rather more about the IF-THEN-ELSE.

Now the IF does the operation of what we are specifying based on the given condition and now if the condition inside the IF block is not satisfied then come ELSE.

It simply does this else do that.

Syntax

IF Condition THEN
Query Statement;
ELSE
Query Statement2;
END IF;

Let us see the real-time example of this IF-THEN-ELSE for this we will be using the same crypto_price table.

So this is the table that will be used in the stored procedure and conditioned with the IF-THEN-ELSE statement.

Let us dive into the Procedure functions we are about to create.

CREATE  PROCEDURE `cryptolist`(Coin_Name varchar(50))
BEGIN
IF Coin_Name='Doge'THEN
UPDATE crypto_price
SET Price=100
WHERE crypto_price.Name='Doge';
ELSE
UPDATE crypto_price
SET Price=5
WHERE crypto_price.Name='XRP';
END IF;
select * from crypto_price;
END
  • So we have created a procedure named cryptolist and passed in the argument with the name Coin_Name.
  • So as we all know procedure always starts with BEGIN.
  • We have created the table as we all know how to query table creation and insert values into the respective data types.
  • We have created the table crypto_price.
  • Now we have used the IF-THEN-ELSE here.

Let see the explanation for it more briefly:

  • It is asked to do that IF the value passed in the argument when calling the procedure is 'Doge'.
  • Update the table we just created crypto_price to set the price to 100 for the respective table name. column name that is precise 'Doge'.
  • If the passed argument is not 'DOGE' then automatically it goes to the ELSE block and executes that query provided inside.
  • using the following query we can call the procedure and use the schema we created and stored to update the price of the crypto every time.

ELSE Scenario:

call cryptolist('randomblabla');

Now we can see that it has executed the else block since 'Doge' is not a match we provided as an argument.

IF Scenario:

call cryptolist('Doge')

Here we can see doge value is updated as the argument passed satisfies the IF block.

Tags