Missing data is common in databases. COALESCE() helps you fill in defaults and avoid null-related issues.
1๏ธโฃ What is COALESCE?
Returns the first non-null value in a list.
SELECT name, COALESCE(phone, 'Not Provided') AS contact
FROM customers;
โ If phone is NULL, it shows โNot Providedโ.
2๏ธโฃ COALESCE with Calculations
Prevent nulls from breaking math.
SELECT name, salary, COALESCE(bonus, 0) AS bonus,
salary + COALESCE(bonus, 0) AS total_income
FROM employees;
โ If bonus is NULL, treat it as 0 to compute total.
3๏ธโฃ Nested COALESCE
Use multiple fallback options.
SELECT name, COALESCE(email, alt_email, 'No Email') AS contact_email
FROM users;
โ Checks email, then alt_email, then default text.
4๏ธโฃ COALESCE in WHERE clause
Filter even when data has nulls.
SELECT *
FROM products
WHERE COALESCE(category, 'Uncategorized') = 'Electronics';
๐ฏ Use COALESCE When You Want To:
โข Replace NULLs with defaults
โข Keep math & filters working
โข Avoid errors in reports or dashboards
๐ Practice Tasks:
1. Replace nulls in city with โUnknownโ
2. Show total amount = price + tax (tax may be null)
3. Replace nulls in description with โNo Info Availableโ
โ Solution for Practice Tasks ๐
1๏ธโฃ Replace NULLs in city with 'Unknown'
SELECT name, COALESCE(city, 'Unknown') AS city
FROM customers;
2๏ธโฃ Show total amount = price + tax (tax may be NULL)
SELECT product_name, price, COALESCE(tax, 0) AS tax,
price + COALESCE(tax, 0) AS total_amount
FROM products;
3๏ธโฃ Replace NULLs in description with 'No Info Available'
SELECT product_name, COALESCE(description, 'No Info Available') AS description
FROM products;
๐ฌ Tap โค๏ธ for more!