Cover Image for MySQL IF()
90 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:

  • condition is the expression or condition that you want to evaluate. If this condition is true, the IF() function will return value_if_true; otherwise, it will return value_if_false.
  • value_if_true is the value that the IF() function returns if the condition is true.
  • value_if_false is the value that the IF() function returns if the condition is false.

Here are some examples of how to use the IF() function in MySQL:

  1. 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;
  1. 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;
  1. 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.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS