MySQL IF() Function

The IF() function in MySQL adds conditional logic to your queries. It allows you to return different values depending on whether a condition is true or false, similar to an if-then-else statement in programming languages.



IF(): Definition and Usage

IF() is very helpful for creating more dynamic and flexible queries. It lets you create different outputs based on whether a condition evaluates to true or false. It's a concise way to add decision-making into your SQL.

Syntax

Syntax

IF(condition, value_if_true, value_if_false)
      

Parameter Values

Parameter Description
condition The condition to be evaluated (must result in TRUE or FALSE). This is required.
value_if_true The value returned if the condition is TRUE. This is required.
value_if_false The value returned if the condition is FALSE. This is required.

Examples

Returning Strings Based on a Condition

This example returns "YES" if 500 is less than 1000, and "NO" otherwise.

Syntax

SELECT IF(500 < 1000, "YES", "NO");
      
Output

YES
      

Returning Numbers Based on a Condition

This example returns 5 if the condition is true, and 10 otherwise.

Syntax

SELECT IF(500 < 1000, 5, 10);
      
Output

5
      

Comparing Strings

This compares two strings and returns "YES" if they're the same, "NO" otherwise. Uses `STRCMP()` for string comparison, which returns 0 for equality.

Syntax

SELECT IF(STRCMP("hello", "bye") = 0, "YES", "NO");
      
Output

NO
      

Conditional Output in a Query

This example adds a 'Result' column based on 'Quantity' in the 'OrderDetails' table. (Assumes an 'OrderDetails' table with 'OrderID' and 'Quantity' columns.)

Syntax

SELECT OrderID, Quantity, IF(Quantity > 10, "MORE", "LESS")
FROM OrderDetails;
      
Output

OrderID | Quantity | Result
--------------------------
(Example data from the OrderDetails table)
      

**Note:** The last example's output will vary depending on the data in your `OrderDetails` table. Each row will have a 'Result' column showing 'MORE' if the `Quantity` exceeds 10 and 'LESS' otherwise.