← Back to Chapters

MySQL IF and CASE Statement

? MySQL IF and CASE Statement

? Quick Overview

The IF and CASE statements in MySQL are used for conditional logic inside SQL queries. They help return different results based on conditions and are widely used to implement business rules directly in the database.

? Key Concepts

  • IF handles simple true/false logic.
  • CASE supports multiple conditions.
  • Both can be used in SELECT, UPDATE, and WHERE clauses.

? IF Statement Syntax

? View Code Example
// IF function checks a condition and returns one of two values
IF(condition, true_value, false_value)

? IF Statement Example

? View Code Example
// Classify products as expensive or cheap based on price
SELECT product_name,
IF(price > 1000, 'expensive', 'cheap') AS price_category
FROM products;

? CASE Statement Syntax

? View Code Example
// CASE evaluates multiple conditions sequentially
CASE
WHEN condition1 THEN result1
WHEN condition2 THEN result2
ELSE default_result
END

? CASE Statement Example

? View Code Example
// Categorize products into multiple price ranges
SELECT product_name,
CASE
WHEN price > 1000 THEN 'expensive'
WHEN price BETWEEN 500 AND 1000 THEN 'moderate'
ELSE 'cheap'
END AS price_category
FROM products;

? Live Output Explanation

The query categorizes products based on price and returns labels such as expensive, moderate, or cheap depending on which condition matches.

? Use Cases

  • Price categorization
  • Grading systems
  • Status labeling
  • Conditional reporting

✅ Tips & Best Practices

  • Use IF for simple binary decisions.
  • Prefer CASE when handling multiple conditions.
  • Always include an ELSE to avoid NULL results.

? Try It Yourself

  • Create a CASE query based on stock quantity.
  • Use IF inside an UPDATE statement.
  • Combine CASE with ORDER BY for custom sorting.