SyntaxStudy
Sign Up
MySQL Control Flow Functions
MySQL Intermediate 6 min read

Control Flow Functions

Control flow functions in MySQL let you add conditional logic directly into your SQL queries. They are a powerful alternative to fetching data and applying IF/ELSE logic in application code.

IF and IFNULL

IF(condition, true_value, false_value) works like a ternary operator. IFNULL(expr, fallback) returns the fallback when the expression is NULL. NULLIF(a, b) returns NULL when a equals b, otherwise returns a.

COALESCE

COALESCE(a, b, c, ...) returns the first non-NULL value from its argument list. This is extremely useful for providing default values when columns may be NULL.

CASE Expression

The CASE expression is the most powerful control flow tool. It supports both simple matching and searched (condition-based) forms, and can appear in SELECT, WHERE, ORDER BY, and more.

  • Simple CASE: CASE col WHEN val THEN result ... END
  • Searched CASE: CASE WHEN condition THEN result ... END
Example
SELECT
    product_name,
    price,
    IF(stock > 0, 'In Stock', 'Out of Stock') AS availability,
    COALESCE(discount_price, price) AS effective_price,
    CASE
        WHEN price < 20  THEN 'Budget'
        WHEN price < 100 THEN 'Mid-range'
        ELSE 'Premium'
    END AS price_tier
FROM products;
Pro Tip

Prefer COALESCE over IFNULL because COALESCE is standard SQL and works in all databases.