Understanding GROUP BY with NULL Values in SQL
📖 Scenario: You work in a small company database team. You have a table that records sales transactions. Some transactions have a known region, but some have NULL because the region was not recorded.You want to learn how SQL groups rows when NULL values appear in the GROUP BY column.
🎯 Goal: Create a table called sales with columns id, region, and amount. Insert some rows including NULL in region. Then write a query that groups sales by region and sums the amount. Observe how NULL values are handled in grouping.
📋 What You'll Learn
Create a table named
sales with columns id (integer), region (text, nullable), and amount (integer).Insert exactly these rows into
sales: (1, 'North', 100), (2, 'South', 150), (3, NULL, 200), (4, 'North', 50), (5, NULL, 300).Write a
SELECT query that groups by region and calculates the total amount per region.Use the exact column names
region and total_amount in the query output.💡 Why This Matters
🌍 Real World
Grouping data by categories often includes missing or unknown values represented as NULL. Understanding how SQL treats NULL in GROUP BY helps in accurate reporting and analysis.
💼 Career
Database developers and analysts frequently write GROUP BY queries. Knowing how NULL values behave ensures correct aggregation and prevents mistakes in business reports.
Progress0 / 4 steps