MySQL IF, IFNULL, CASE and Pivot-Style Reports

MySQL 55 min min read Updated: Nov 27, 2026 Intermediate
MySQL IF, IFNULL, CASE and Pivot-Style Reports
Intermediate Topic 3 of 3

IF() and IFNULL()

sql SELECT name, stock, IF(stock = 0, 'Out of stock', IF(stock < 10, 'Low', 'OK')) AS level FROM products ORDER BY id;

Result:

namestocklevel
Laptop15OK
Phone30OK
Headphones100OK
Desk10OK
Chair25OK
Notebook500OK
Pen Pack300OK
Lamp0Out of stock

IF(test, a, b) is MySQL-only shorthand. The portable form is CASE.

sql SELECT name, IFNULL(email, 'no email') AS email, COALESCE(email, city, 'unknown') AS contact FROM customers ORDER BY id;

Result:

nameemailcontact
Asha Raoasha@example.comasha@example.com
Ben Carterben@example.comben@example.com
Chen Weichen@example.comchen@example.com
Dina Cohenno emailTel Aviv
Eli Browneli@example.comeli@example.com
Fatima Khanfatima@example.comfatima@example.com

CASE

sql SELECT name, price, CASE WHEN price < 20 THEN 'Budget' WHEN price < 200 THEN 'Mid' ELSE 'Premium' END AS tier FROM products ORDER BY price;

Result:

namepricetier
Notebook3.50Budget
Pen Pack5.00Budget
Lamp45.00Mid
Headphones79.00Mid
Chair129.00Mid
Desk249.00Premium
Phone599.00Premium
Laptop899.00Premium

NULLIF: Avoid Divide by Zero

sql SELECT name, ROUND(price / NULLIF(stock, 0), 2) AS price_per_unit FROM products ORDER BY id;

Result:

nameprice_per_unit
Laptop59.93
Phone19.97
Headphones0.79
Desk24.90
Chair5.16
Notebook0.01
Pen Pack0.02
LampNULL

Division by zero in MySQL returns NULL (with a warning) in normal queries and raises an error in strict INSERT or UPDATE. NULLIF makes the intent clear.

Conditional Aggregation

sql SELECT customer_id, COUNT(*) AS orders, SUM(status = 'shipped') AS shipped, SUM(status = 'pending') AS pending, SUM(status = 'cancelled') AS cancelled FROM orders GROUP BY customer_id ORDER BY customer_id;

Result:

customer_idordersshippedpendingcancelled
13210
23201
32110
51100
61100

In MySQL a comparison is 1 or 0, so SUM(status = 'shipped') counts matches. In other databases write SUM(CASE WHEN ... THEN 1 ELSE 0 END).

Pivot: Rows to Columns

sql SELECT category, SUM(CASE WHEN price < 100 THEN 1 ELSE 0 END) AS under_100, SUM(CASE WHEN price >= 100 THEN 1 ELSE 0 END) AS from_100 FROM products GROUP BY category ORDER BY category;

Result:

categoryunder_100from_100
Electronics12
Furniture12
Stationery20

MySQL has no PIVOT keyword. The column list is fixed in the query. For unknown columns, build the SQL text with GROUP_CONCAT and run it with a prepared statement.

Dynamic Pivot with a Prepared Statement

sql SET @cols = (SELECT GROUP_CONCAT(DISTINCT CONCAT('SUM(status = ''', status, ''') AS `', status, '`') ORDER BY status) FROM orders); SET @sql = CONCAT('SELECT customer_id, ', @cols, ' FROM orders GROUP BY customer_id ORDER BY customer_id'); PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;

Result:

customer_idcancelledpendingshipped
1012
2102
3011
5001
6001
Only build SQL from trusted values Here the column names come from your own table. Never build SQL text from user input, because it opens the door to SQL injection.

Ordering with CASE and FIELD

sql SELECT id, status FROM orders ORDER BY FIELD(status, 'pending', 'shipped', 'delivered', 'cancelled'), id;

Result:

idstatus
4pending
7pending
1shipped
2shipped
3shipped
6shipped
8shipped
9shipped
10shipped
5cancelled

Common Beginner Mistakes

MistakeWhat happensFix
CASE without ELSENULL for other rowsAdd ELSE
Using IFNULL with 3 argumentsErrorUse COALESCE
Expecting PIVOT syntaxSyntax errorUse CASE with SUM
Dividing by a possible zeroNULL or errorUse NULLIF
Building SQL from user inputSQL injectionUse only trusted names

Practice

  1. Label customers by order count with CASE.
  2. Make a report with one column per order status.
  3. Sort orders with custom status order.
  4. Show revenue per category as separate low and high price columns.

Conclusion

IF, IFNULL, COALESCE, NULLIF and CASE shape values. Conditional aggregation with SUM(CASE ...) creates pivot reports, since MySQL has no PIVOT.

Quick Summary: IF, IFNULL, COALESCE, NULLIF, CASE, conditional aggregation, pivot, FIELD.

Get Newsletter

Subscibe to our newsletter and we will notify you about the newest updates on Edugators