SQL

COALESCE / NULLIF — Null Handling

admin by @admin ADMIN
16m ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
`COALESCE(a, b, c)` returns the first non-NULL value — perfect for fallbacks. `NULLIF(a, b)` returns NULL when a equals b — handy for "treat sentinel as null".
SQL
Raw
-- Show display_name, fall back to email, fall back to "Anonymous"
SELECT id,
       COALESCE(display_name, email, 'Anonymous') AS shown_name
FROM   users;

-- NULLIF — divide by zero protection
SELECT amount, qty,
       amount / NULLIF(qty, 0) AS unit_price   -- returns NULL instead of error
FROM   line_items;

-- Treat empty string as NULL (common normalization)
UPDATE users
SET email = NULLIF(TRIM(email), '');

-- Difference between COALESCE and ISNULL/IFNULL:
--   COALESCE  — standard SQL, variadic, returns the type of the first non-null
--   IFNULL    — MySQL, takes exactly 2 args
--   ISNULL    — SQL Server, takes exactly 2 args
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.