Replace null with 0 in MySQL
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
In MySQL, NULL represents a missing or unknown value. When NULL appears in arithmetic expressions, the result is always NULL (5 + NULL = NULL). To substitute NULL with 0 (or any default), use IFNULL(), COALESCE(), or a CASE expression. IFNULL(column, 0) is the simplest MySQL-specific option, while COALESCE(column, 0) is the SQL-standard portable version. These functions work in SELECT, WHERE, ORDER BY, and aggregate contexts.
Using IFNULL()
IFNULL() takes exactly two arguments. If the first argument is NULL, it returns the second. Otherwise, it returns the first unchanged. This is MySQL-specific.
Using COALESCE()
COALESCE() is the SQL-standard function. It accepts any number of arguments and returns the first non-NULL value. For a single column with a default, it behaves identically to IFNULL().
Using CASE Expression
CASE is verbose but allows combining NULL checks with other conditions in a single expression.
In Aggregate Functions
The choice between letting aggregates skip NULLs versus replacing them with 0 depends on your business logic. Skipping NULLs gives a more accurate average, while replacing with 0 includes "no response" as a zero score.
In WHERE and ORDER BY
Updating NULL to 0 Permanently
If NULL should never appear in a column, add a NOT NULL constraint with a DEFAULT value to prevent it at the schema level.
In JOIN Results
LEFT JOINs are a common source of unexpected NULLs. Wrapping the aggregated column in IFNULL ensures customers with no orders show 0 instead of NULL.
Common Pitfalls
- Using = NULL instead of IS NULL:
WHERE price = NULLreturns no rows becauseNULL = NULLevaluates toNULL(unknown), notTRUE. Always useIS NULLorIS NOT NULL. - NULL in arithmetic:
5 + NULL = NULL,10 * NULL = NULL. Any arithmetic withNULLproducesNULL. Wrap each nullable operand inIFNULL()before calculating. - IFNULL vs COALESCE portability:
IFNULL()is MySQL-specific. If you migrate to PostgreSQL, Oracle, or SQL Server, useCOALESCE()for cross-database compatibility. - AVG with replaced NULLs changes the result:
AVG(score)skips NULLs (divides by non-NULL count).AVG(IFNULL(score, 0))includes them as zeros (divides by total count), which lowers the average. - Forgetting NULLs in GROUP BY:
GROUP BYtreats allNULLvalues as equal and groups them together. If you need NULLs in separate groups, replace them with a sentinel value before grouping.
Summary
IFNULL(column, 0)is the simplest MySQL way to replace NULL with 0COALESCE(column, 0)is the SQL-standard equivalent and supports multiple fallback values- Aggregate functions (
SUM,AVG,COUNT(col)) skip NULLs by default — wrap inIFNULLif you want to treat them as 0 - Use
UPDATE ... SET col = IFNULL(col, 0)to permanently replace NULLs in the table - Add
NOT NULL DEFAULT 0constraints to prevent future NULLs at the schema level

