Using COALESCE for NULL Handling in PostgreSQL
📖 Scenario: You are managing a small online store database. Some customers have not provided their phone numbers, so those entries are NULL. You want to create a query that shows each customer's name and phone number, but if the phone number is missing, it should show 'No Phone Provided' instead.
🎯 Goal: Build a SQL query using COALESCE to replace NULL phone numbers with the text 'No Phone Provided'.
📋 What You'll Learn
Create a table called
customers with columns id (integer), name (text), and phone (text).Insert exactly three customers with these details: (1, 'Alice', '123-456-7890'), (2, 'Bob', NULL), (3, 'Charlie', NULL).
Write a SELECT query that shows
name and phone but replaces NULL phone values with 'No Phone Provided' using COALESCE.Alias the replaced phone column as
contact_phone.💡 Why This Matters
🌍 Real World
Handling missing or NULL data is common in real databases. COALESCE helps show friendly default values instead of NULL.
💼 Career
Knowing how to manage NULL values with COALESCE is essential for database querying and reporting in many jobs.
Progress0 / 4 steps