MySQL IF() function

Easy Solution Web : MySQL Tutorials

IF() function is one of the most interesting functions in MySQL as it helps a lot while implementing a complex logic in a simple query.

IF FUNCTION takes three parameter

IF(CONDITION STATEMENT, STATEMENT FOR TRUE CASE, STATEMENT FOR FALSE CASE)

We use IF function mostly to generate calculated column which is used to show the result in the more meaningful way.

For Example:

You want to generate a report of the total order placed in a month and you want to submit this report to your Manager, who don’t have knowledge of technical term. So, in that case, you will need IF Function.

Here CONDITION STATEMENT is a statement which will return TRUE or FALSE on the basis of which, will run the STATEMENT FOR TRUE CASE or STATEMENT FOR FALSE CASE and return a value.

For Example:

CONDITION STATEMENT  if return TRUE

then STATEMENT FOR TRUE CASE will execute

select IF(true,"TRUE CASE", "FALSE CASE");

MySQL - IF FUNCTION

 

 

CONDITION STATEMENT  if return FALSE

then STATEMENT FOR FALSE CASE will execute

select IF(false,"TRUE CASE", "FALSE CASE");

MySQL - IF FUNCTION false case

 

 

We can also implement nested IF() in MySQL i.e. IF() within IF()

Nested if in case of a TRUE case:

IF(CONDITION STATEMENT, IF(CONDITION STATEMENT, STATEMENT FOR TRUE CASE, STATEMENT FOR FALSE CASE), STATEMENT FOR FALSE CASE)

For Example:

select IF(true,IF(true,"NESTED TRUE CASE", "NESTED  FALSE CASE"), "FALSE CASE");

Nested if in case of a FALSE case:

IF(CONDITION STATEMENT, STATEMENT FOR TRUE CASE, IF(CONDITION STATEMENT, STATEMENT FOR TRUE CASE, STATEMENT FOR FALSE CASE))

For Example:

select IF(true,"TRUE CASE", IF(true,"NESTED TRUE CASE", "NESTED  FALSE CASE"));

 

IF() with SELECT Statement

Inside IF function we are also able to use select statement but it should return single value instead multiple rows or columns

select *, if(column_three > 2 ,(select count(1) from table_one where column_three > 2), "Column_one is smaller than 2") from table_one

MySQL - IF Function with select

We can implement SELECT statement with nested IF() if you need.

IF() can be used in simple MySQL Query or in PL/SQL