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