Which of the following SQL queries correctly groups rows by a column that may contain NULL values?
easy📝 Syntax Q12 of 15
SQL - GROUP BY and HAVING
Which of the following SQL queries correctly groups rows by a column that may contain NULL values?
ASELECT category, COUNT(*) FROM products GROUP BY category;
BSELECT category, COUNT(*) FROM products GROUP BY category WHERE category IS NOT NULL;
CSELECT category, COUNT(*) FROM products WHERE category IS NOT NULL GROUP BY category;
DSELECT category, COUNT(*) FROM products GROUP BY category HAVING category IS NOT NULL;
Step-by-Step Solution
Solution:
Step 1: Check GROUP BY syntax with NULLs
SELECT category, COUNT(*) FROM products GROUP BY category; uses correct syntax: grouping by category including NULLs. GROUP BY works with NULL values without extra filters.
Step 2: Analyze other options
Options A and D misuse WHERE and HAVING clauses with GROUP BY. SELECT category, COUNT(*) FROM products WHERE category IS NOT NULL GROUP BY category; filters out NULLs before grouping, which is valid but excludes NULL groups.
Final Answer:
SELECT category, COUNT(*) FROM products GROUP BY category; -> Option A
Quick Check:
GROUP BY with NULLs needs no special filter [OK]
Quick Trick:GROUP BY works directly with NULLs, no WHERE needed [OK]
Common Mistakes:
MISTAKES
Using WHERE after GROUP BY (syntax error)
Filtering NULLs before grouping unintentionally
Misusing HAVING clause for filtering NULLs
Master "GROUP BY and HAVING" in SQL
9 interactive learning modes - each teaches the same concept differently