mysql
  1. mysql-if

IF() - MySQL Control Flow Function

In MySQL, the IF() function is a control flow function that allows you to conditionally execute statements based on a specified condition. In this tutorial, we'll discuss the syntax, example, output, explanation, use, important points, and summary of the IF() function in MySQL.

Syntax

The basic syntax for the IF() function is as follows:

IF(condition, value_if_true, value_if_false)
  • condition: The condition to evaluate.
  • value_if_true: The value to return if the condition is true.
  • value_if_false: The value to return if the condition is false.

Example

Suppose we have a table called employees containing the following data:

id name salary
1 John 50000
2 Jane 65000
3 Jack 75000

We can use the IF() function to create a calculated column called bonus, which returns a bonus of 10% if the employee's salary is greater than 60000, and 5% otherwise:

SELECT name, salary, IF(salary > 60000, salary * 0.1, salary * 0.05) as bonus
FROM employees;

Output

When we run the example query above, we get the following result:

name salary bonus
John 50000 2500
Jane 65000 6500
Jack 75000 7500

Explanation

In the example above, we used the IF() function to create a calculated column called bonus. The function checks if the employee's salary is greater than 60000. If it is, it returns the salary multiplied by 0.1 (i.e., a 10% bonus). Otherwise, it returns the salary multiplied by 0.05 (i.e., a 5% bonus).

Use

The IF() function is useful for creating conditional expressions and calculated columns in MySQL queries. It allows you to execute different statements based on a given condition. This makes queries more flexible and less verbose.

Important Points

  • The IF() function is a control flow function in MySQL.
  • It allows you to conditionally execute statements based on a specified condition.
  • It takes three arguments: the condition to evaluate, the value to return if the condition is true, and the value to return if the condition is false.

Summary

In this tutorial, we discussed the IF() function in MySQL. We covered the syntax, example, output, explanation, use, and important points of the function. With this knowledge, you can now use the IF() function to create conditional expressions and calculated columns in your MySQL queries.

Published on: