iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

SQL NULL Functions

Every major engine ships a small family of helpers for handling NULL values. They differ by name across vendors.

Per-vendor cheat sheet

DBFunctionBehaviour
MySQL / MariaDBIFNULL(x, fallback)Returns x, or fallback if NULL.
SQL ServerISNULL(x, fallback)Same as MySQL's IFNULL.
MS AccessNz(x, fallback)Same idea.
All major DBsCOALESCE(x, y, z, …)Returns the first non-NULL argument. Portable.
All major DBsNULLIF(a, b)Returns NULL if a = b, else a. Useful for "avoid divide by zero".

Examples

SQL
SELECT name, COALESCE(phone, 'n/a') AS phone
FROM customers;

-- Avoid divide-by-zero
SELECT total, NULLIF(qty, 0) AS qty,
       total / NULLIF(qty, 0) AS unit_price
FROM line_items;

Why COALESCE wins

  • Portable — works in every major engine.
  • Takes any number of arguments — you can chain fallbacks.
  • Short-circuits — stops at the first non-NULL.
Tip: Reach for COALESCE by default. Save IFNULL/ISNULL for codebases that already use them.

Example

Example
SELECT name, COALESCE(phone, 'n/a') AS phone
FROM customers;
Try it Yourself »

Exercise

Portable function that returns the first non-NULL value.

('phone', 'n/a')

Test yourself

Q1. Portable replacement for IFNULL/ISNULL/Nz is…
Q2. NULLIF(a, b) returns NULL when…
Q3. A common use of NULLIF is…

Discussion

Loading…