Handling NULLs in JOIN Conditions
📖 Scenario: You work at a company that manages customer orders. Some orders have assigned sales representatives, but some do not yet have one assigned, so the sales_rep_id can be NULL.You want to create a report that shows all orders along with the sales representative's name if assigned, or show 'No Rep Assigned' if not.
🎯 Goal: Create two tables orders and sales_reps. Then write a SQL query that joins these tables on sales_rep_id, correctly handling NULL values so that orders without a sales rep still appear in the results with a placeholder text.
📋 What You'll Learn
Create a table called
orders with columns order_id (integer), customer_name (text), and sales_rep_id (integer, can be NULL).Create a table called
sales_reps with columns sales_rep_id (integer) and rep_name (text).Insert the exact data provided into both tables.
Write a SQL query that LEFT JOINs
orders with sales_reps on sales_rep_id, handling NULLs so that orders without a sales rep show 'No Rep Assigned' in the output.Use
COALESCE or CASE to replace NULL sales rep names with 'No Rep Assigned'.💡 Why This Matters
🌍 Real World
Handling NULLs in JOIN conditions is common in real databases where relationships may be optional, such as orders without assigned sales reps.
💼 Career
Database developers and analysts often write queries that must handle NULLs correctly to produce accurate reports and avoid missing data.
Progress0 / 4 steps