Using COALESCE for NULL Handling in SQL
📖 Scenario: You work for a small bookstore that keeps track of book sales. Some books have missing sales data (NULL values) because they are new or out of stock. You want to create a report that shows the sales numbers, but replaces any missing sales with zero to make the report clearer.
🎯 Goal: Build an SQL query that uses the COALESCE function to replace NULL sales values with zero in the sales report.
📋 What You'll Learn
Create a table called
books with columns id, title, and sales.Insert the exact data rows with some
sales values as NULL.Write a query that selects
title and uses COALESCE to show sales with NULL replaced by 0.Alias the replaced sales column as
sales_report.💡 Why This Matters
🌍 Real World
Handling missing data is common in real databases. Using COALESCE helps create clean reports without confusing NULL values.
💼 Career
Database developers and analysts often use COALESCE to ensure queries return meaningful data for reports and dashboards.
Progress0 / 4 steps