0
0
MySQLquery~5 mins

IF function in MySQL

Choose your learning style9 modes available
Introduction

The IF function helps you choose between two values based on a condition. It works like a simple question: if something is true, show one thing; if not, show another.

You want to check if a number is positive or negative and show a message.
You want to label people as 'Adult' or 'Minor' based on their age.
You want to give a discount only if the purchase amount is above a certain value.
You want to display 'Yes' or 'No' depending on whether a product is in stock.
Syntax
MySQL
IF(condition, value_if_true, value_if_false)
The condition is a test that returns true or false.
The function returns value_if_true if the condition is true, otherwise it returns value_if_false.
Examples
This checks if 5 is greater than 3. It returns 'Yes' because the condition is true.
MySQL
SELECT IF(5 > 3, 'Yes', 'No');
This labels each user as 'Adult' or 'Minor' depending on their age.
MySQL
SELECT IF(age >= 18, 'Adult', 'Minor') FROM users;
This shows if each product is available or not.
MySQL
SELECT product_name, IF(stock > 0, 'In stock', 'Out of stock') FROM products;
Sample Program

This creates a table of people with their ages, then shows if each person is an Adult or Minor using the IF function.

MySQL
CREATE TABLE people (name VARCHAR(20), age INT);
INSERT INTO people VALUES ('Alice', 22), ('Bob', 15), ('Carol', 18);
SELECT name, age, IF(age >= 18, 'Adult', 'Minor') AS status FROM people;
OutputSuccess
Important Notes

The IF function is different from the CASE statement but can be easier for simple true/false checks.

Make sure the condition returns a boolean result (true or false).

Summary

The IF function chooses between two values based on a condition.

It is useful for simple decisions inside queries.

Use it to make your query results easier to understand.