Tsallaka zuwa abun ciki
Justice Tech School

COALESCE and NULL Handling

COALESCE returns the first value that is not NULL, which is perfect for giving NULLs a default. IFNULL (MySQL, SQLite) and ISNULL (SQL Server) do the same for two values. NULLIF turns a value into NULL.

Example
SELECT name, COALESCE(score, 0) AS score_or_zero
FROM students
WHERE id IN (7, 8);

Result

name  | score_or_zero
Sipho | 59
Esi   | 0
Example
SELECT COUNT(*) AS rows, ROUND(AVG(score), 2) AS avg_ignoring_null, ROUND(AVG(COALESCE(score, 0)), 2) AS avg_with_zero
FROM students;

Result

rows | avg_ignoring_null | avg_with_zero
8    | 76.71             | 67.13

Exercise

Use 0 when the value is NULL.

SELECT (score, 0) FROM students;

Quiz Test

What does COALESCE(NULL, 5, 9) return?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.