Introduction
Aggregates help us summarize data, but NULL values can hide or change results. Handling NULLs correctly ensures accurate summaries.
Jump into concepts and practice - no test required
SELECT AGGREGATE_FUNCTION(column_name) FROM table_name;
SELECT COUNT(column_name) FROM table_name;
SELECT COUNT(*) FROM table_name;
SELECT AVG(column_name) FROM table_name;
SELECT SUM(COALESCE(column_name, 0)) FROM table_name;
CREATE TABLE sales ( id INT, amount INT ); INSERT INTO sales (id, amount) VALUES (1, 100), (2, NULL), (3, 200), (4, NULL); SELECT COUNT(amount) AS count_non_null, COUNT(*) AS count_all, AVG(amount) AS average_amount, SUM(COALESCE(amount, 0)) AS sum_with_nulls_handled FROM sales;
NULL values in any column?sales?orders with column discount containing values (10, NULL, 10, NULL, 15), what is the result of this query?SELECT AVG(COALESCE(discount, 0)) FROM orders;
score column:SELECT COUNT(score) + COUNT(NULL) FROM results;
employees with a nullable bonus column. You want to calculate the total bonus, treating NULL as zero, but only for employees with a salary above 50000. Which query correctly does this?