MySQL IF FUNCTION


The MySQL IF function is used to perform conditional logic within a query or statement. It operates similarly to an IF-THEN-ELSE statement in programming.

Syntax
If(condition,value_if_true,value_if_false) 
Parameters
  • condition : The condition to evaluate.
  • value_if_true : The value returned if the condition is TRUE.
  • value_if_false : The value returned if the condition is FALSE.
Demo Database:
  • Table Name : orders
order_no order_date customer_id total_amount status
2021001 2021-05-13 1 1545.00 Delivered
2021002 2021-05-13 2 18000.00 Delivered
2021003 2021-05-14 3 10000.00 Pending
2021004 2021-05-15 4 1450.00 Delivered
2021005 2021-05-16 5 4680.00 Pending
2021006 2021-05-17 6 10000.00 Pending
2021007 2021-05-18 7 5475.00 Delivered
2021008 2021-05-19 8 4337.00 Pending
Basic Example
Example
SELECT IF (1 > 0,'True','False') AS RESULT;  
Try it Yourself
Condition With Query

MySQL, the IF function requires three arguments: the condition, the value if the condition is true, and the value if the condition is false.:

Example
select total_amount,if(total_amount>5000,"Discount Applied","No Discount") as disount from orders;
Try it Yourself
Check the count of order status where Delivered and Pending in single Query

The query calculates the total amounts for orders based on their status (Delivered and Pending) from the orders:

SUM(IF(condition, value_if_true, value_if_false)):

  • condition : A condition to evaluate, in this case, whether the status is equal to 'Delivered' or 'Pending'.
  • value_if_true : The value to use if the condition is true, display total_amount value.
  • value_if_false : The value to use if the condition is false, which is 0 here.
  • DeliveredAmount : The total_amount for rows where status is 'Delivered'.
  • PendingAmount : The total_amount for rows where status is 'Pending'.
Example
SELECT 
  sum(if(status='Delivered',total_amount,0)) as DeliveredAmount, 
  sum(if(status='Pending',total_amount,0))  as PendingAmount 
 FROM orders 
Try it Yourself