✏️ Explanatory Question

What are control flow functions like IF, IFNULL, CASE, and COALESCE?

👁 11 Views
📘 Detailed Answer
🟢 Easy
💡

Answer with Explanation

33

What are control flow functions like IF, IFNULL, CASE, and COALESCE?

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.

The Four Key Functions

  • IF(condition, true_val, false_val): A simple ternary — returns one of two values based on a condition.
  • IFNULL(expr, alt): Returns expr if it's not NULL, otherwise returns alt. Handles exactly one fallback.
  • COALESCE(v1, v2, ...): Returns the first non-NULL value from a list. A more flexible, multi-argument IFNULL.
  • CASE: A full multi-branch conditional (like if/else-if/else) — the most powerful of the four.
IFNULL vs COALESCE: 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.

Quick Reference

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

Quick Example — All Four

-- 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;
Two forms of CASE: The searched CASE (shown above, uses WHEN condition) and the simple CASE (CASE column WHEN value THEN ...). The searched form is more flexible for ranges.
Interviewer tip: The one-liner they want — "IF handles a two-way condition, IFNULL replaces a NULL with one fallback, COALESCE returns the first non-NULL from many values, and CASE handles full multi-branch logic."