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.
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.
IF(condition, value_if_true, value_if_false)
SELECT IF(5 > 3, 'Yes', 'No');
SELECT IF(age >= 18, 'Adult', 'Minor') FROM users;
SELECT product_name, IF(stock > 0, 'In stock', 'Out of stock') FROM products;
This creates a table of people with their ages, then shows if each person is an Adult or Minor using the IF function.
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;
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).
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.
IF function do?IF function?employees with a column salary, what will this query return?SELECT name, IF(salary >= 5000, 'High', 'Low') AS salary_level FROM employees;
SELECT name, IF salary > 1000, 'Rich', 'Poor' AS status FROM users;
IF functions to achieve this?Pass the test and this pattern moves unknown