Unit 2, Checking AI-written SQL · Checking NULL handling
Checking AI-written SQL: where do the NULLs go?
Check the AI: the average sale price
Aggregate functions skip NULLs. COUNT(column), SUM, AVG, MIN and MAX all ignore missing values without telling you. When AI writes an aggregate over a column that can be NULL, ask what happens to those rows.
SELECT COUNT(*) AS products,
COUNT(discount) AS discounted
FROM products;Review the AI's query
Someone asked an AI assistant: What is the average sale price across all products in the catalog, rounded to cents? Products with no discount sell at full price. It wrote this query:
SELECT ROUND(AVG(price * (1 - discount)), 2) AS avg_sale_price
FROM products;
Does it answer the question?
- Yes, it answers the question
- No: products with no discount drop out of the average
- No: it should use SUM instead of AVG
Show the answer
No: products with no discount drop out of the average. For a product with no discount, price * (1 - NULL) is NULL, and AVG quietly skips NULLs. So this is the average of the 7 discounted products only, not all 14. The number looks reasonable, which is exactly why it would slip into a report.
Then fix it
Now fix the AI's query so every product counts, with no discount meaning full price.
Tables you will use: products
Try it in your browserFree, no sign-up. Your query is checked as you go.