Tuesday, December 24, 2024

MySQL IF() Function

 The IF() function in MySQL is used to return a value based on a condition. It is a conditional function that takes three arguments:

IF(condition, value_if_true, value_if_false)
  • condition: The condition to be evaluated (e.g., an expression or comparison).
  • value_if_true: The value returned if the condition is true.
  • value_if_false: The value returned if the condition is false.

Example 1: Basic Example

SELECT IF(10 > 5, 'Yes', 'No');

Output: 'Yes'
Explanation: Since 10 > 5 is true, the function returns 'Yes'.

Example 2: Using IF with Columns

SELECT name, IF(age >= 18, 'Adult', 'Minor') AS status
FROM users;

Output:

name status
John Adult
Emily Minor
Tom Adult

Explanation: This query checks if a person's age is greater than or equal to 18 and returns 'Adult' or 'Minor' accordingly.

Example 3: Using IF in an UPDATE Query

UPDATE employees
SET salary = IF(experience > 5, salary * 1.1, salary)
WHERE department = 'Sales';

Explanation: For employees in the Sales department, if their experience is greater than 5 years, their salary will be increased by 10%, otherwise, it remains the same.

The IF() function is a great tool for implementing conditional logic directly within SQL queries.

No comments:

Post a Comment