
246 views
MySQL IF()
The MySQL IF() function is a built-in function that allows you to perform conditional operations within a SQL query. It is often used to return one value if a specified condition is true and another value if the condition is false.
The basic syntax of the IF() function is as follows:
IF(condition, value_if_true, value_if_false)
Here’s how it works:
conditionis the expression or condition that you want to evaluate. If this condition is true, theIF()function will returnvalue_if_true; otherwise, it will returnvalue_if_false.value_if_trueis the value that theIF()function returns if theconditionis true.value_if_falseis the value that theIF()function returns if theconditionis false.
Here are some examples of how to use the IF() function in MySQL:
- Return ‘Yes’ if a student’s score is greater than or equal to 70; otherwise, return ‘No’:
SELECT student_name, IF(score >= 70, 'Yes', 'No') as passed
FROM student_scores;
- Calculate a discounted price for products. If the product price is greater than $100, apply a 10% discount; otherwise, return the original price:
SELECT product_name, price, IF(price > 100, price * 0.9, price) as discounted_price
FROM products;
- Determine if an order was placed more than 30 days ago. If so, mark it as ‘Stale’; otherwise, mark it as ‘Recent’:
SELECT order_id, order_date, IF(DATEDIFF(NOW(), order_date) > 30, 'Stale', 'Recent') as order_status
FROM orders;
The IF() function is a versatile tool in SQL for performing conditional operations within your queries. It can be used to create calculated columns, apply discounts, categorize data, and more, depending on the specified conditions. It is especially useful for creating informative reports and making data-driven decisions in your database queries.