Python SQL Null Functions: COALESCE, IFNULL, ISNULL & NULLIF
SQL provides dedicated scalar functions to manage missing data gracefully: `COALESCE(val1, val2, ...)` returns the first non-null value from an argument list; `NULLIF(a, b)` returns `NULL` if arguments are equal (crucial for preventing division-by-zero errors).
"`COALESCE` is a prioritized backup contact list: "Try calling mobile phone; if missing (NULL), try home phone; if missing, fall back to company main desk.""
Deep Dive: How It Works
COALESCE (ANSI Universal): `COALESCE(work_email, personal_email, 'no-reply@domain.com')`. Accepts unlimited arguments, evaluating left-to-right.
Engine Variants: `IFNULL(a, b)` (MySQL/SQLite 2-arg shorthand), `ISNULL(a, b)` (SQL Server), `NVL(a, b)` (Oracle). `COALESCE` is universally portable across ALL engines.
Preventing Division-by-Zero with NULLIF: `total_sales / NULLIF(total_orders, 0)`. If total_orders is 0, NULLIF turns it into NULL, returning NULL instead of crashing the database!
Syntax Blueprint
SELECT name, COALESCE(discount_rate, 0.0) AS applied_discount, total_revenue / NULLIF(units_sold, 0) AS avg_unit_price FROM products;
Use COALESCE for default fallbacks and NULLIF to prevent division-by-zero crashes.
Core Rules to Remember



Common Beginner Traps & How to Fix Them
Dividing by raw columns `sales / count` without checking for zero.Why it happens: A single 0 value in the divisor aborts the entire production query with "Division by zero".
How to fix: Always wrap the divisor with `NULLIF(divisor, 0)`.
Live Interactive Example
Hit Run Code to see it liveYour Turn: Micro Challenge
No pressure! Edit the starter code below and test your solution with instant feedback.
Provide Default with COALESCE
Select `name`, `COALESCE(nickname, name) AS display_name` from `users`.
Finished reading and practicing?
Mark this lesson as completed to update your course progress.