✏️ Explanatory Question
Level: Intermediate — These add conditional logic directly inside your SQL queries.
Control flow functions let you apply "if-then-else" logic within a query, returning different values based on conditions. They are extremely useful for transforming and cleaning data on the fly.
expr if it's not NULL, otherwise returns alt. Handles exactly one fallback.IFNULL() takes only two arguments, while COALESCE() takes many and returns the first non-NULL. COALESCE is also ANSI SQL standard (portable across databases); IFNULL is MySQL-specific.
| Function | Args | Returns |
|---|---|---|
| IF() | 3 | True or false value |
| IFNULL() | 2 | Value or single fallback |
| COALESCE() | Many | First non-NULL value |
| CASE | Many branches | Matched branch result |
-- IF: simple two-way choice
SELECT name, IF(salary > 50000, 'High', 'Low') AS salary_band
FROM employees;
-- IFNULL: replace NULL with a default
SELECT name, IFNULL(phone, 'Not Provided') AS phone
FROM employees;
-- COALESCE: first non-NULL from several columns
SELECT name, COALESCE(mobile, landline, email, 'No Contact') AS contact
FROM employees;
-- CASE: multi-branch logic
SELECT name, marks,
CASE
WHEN marks >= 90 THEN 'A'
WHEN marks >= 75 THEN 'B'
WHEN marks >= 50 THEN 'C'
ELSE 'Fail'
END AS grade
FROM students;
WHEN condition) and the simple CASE (CASE column WHEN value THEN ...). The searched form is more flexible for ranges.