Skip to content

Handling Missing Values

As we learned in Module 1, NULL values can break logic and calculations. To write resilient SQL, you need specific functions to replace NULLs with defaults or to create NULLs when they are needed for safety.

These two functions are the “Guardians” of your data integrity.

  • COALESCE(val1, val2, ... valN): Returns the first non-null value in the list.
  • NULLIF(val1, val2): Returns NULL if val1 equals val2. Otherwise, it returns val1.

In math, dividing by zero is undefined. In SQL, it crashes your query. NULLIF is the standard way to prevent “Division by Zero” errors by turning the zero into a NULL. Since any number divided by NULL is NULL, the query survives.

COALESCE is often used to provide fallback values for reports.

COALESCE Fallback
SELECT COALESCE(PhoneNumber, 'No Phone Provided') FROM Customers;

If PhoneNumber is NULL, the user sees “No Phone Provided” instead of a blank space or an error.

You could use a CASE statement: CASE WHEN PhoneNumber IS NULL THEN 'No Phone Provided' ELSE PhoneNumber END

However, COALESCE is more concise and can handle multiple fallbacks (e.g., Check Phone, then Email, then “No Contact”).

NULLIF is commonly used to clean data or prevent errors.

Imagine a database where an empty string '' was used to mean “No Data”. You want to treat those as proper SQL NULLs. NULLIF(ColumnName, '')

Safe Division
SELECT Sales / NULLIF(ItemsSold, 0) FROM Reports;

We have a ProductStock table:

NameRetailPriceDiscountPriceStockCount
Widget100.0080.0050
Gadget50.00NULL10
Gizmo20.0015.000

Task: Find the “Best Price” (Discount if available, else Retail) and calculate the Stock Ratio.

Section titled “Task: Find the “Best Price” (Discount if available, else Retail) and calculate the Stock Ratio.”
Cleanup in Action
SELECT
Name,
COALESCE(DiscountPrice, RetailPrice) AS BestPrice,
100.0 / NULLIF(StockCount, 0) AS ScarcityFactor
FROM ProductStock;
NameBestPriceScarcityFactor
Widget80.002.0
Gadget50.0010.0
Gizmo15.00NULL

Note: Gizmo’s ScarcityFactor is NULL because we used NULLIF to prevent division by zero.

COALESCE is a “Variadic” function—it can take an unlimited number of arguments. Internally, the database engine implements COALESCE as a shorthand for a searched CASE expression.

COALESCE(a, b, c) is translated by the query optimizer to:

Optimizer Translation
CASE
WHEN a IS NOT NULL THEN a
WHEN b IS NOT NULL THEN b
ELSE c
END

Because it’s a CASE expression, it also supports Short-Circuiting. If a is not null, the engine never even looks at b or c. This is useful if b is a complex, expensive subquery or calculation.