COALESCE: Use the first non-NULL value
Core idea
COALESCE returns the first argument that is not NULL, reading arguments from left to right. It is useful for displaying a fallback when a value is missing. It does not update the source column.
Minimal example
SELECT COALESCE(NULL, 0, 7), COALESCE(NULL, NULL);Expected SQLite rows:
0 | NULLHow it works
Syntax: COALESCE(value, fallback, ...). When all arguments are NULL, the result is NULL. Zero and empty text are not NULL in SQLite and PostgreSQL. In the score example, -1 is an explicitly chosen display sentinel, not a real score; retain the original value alongside it. PostgreSQL requires arguments convertible to a common result type.
Practical example
SELECT id, score, COALESCE(score, -1) AS display_score FROM sort_scores ORDER BY id;Expected SQLite rows:
1 | 10 | 102 | NULL | -13 | 0 | 04 | NULL | -1Common mistake and practice
Do not replace missing measurements with zero unless the business rule justifies it. Practice: change the display sentinel to -99 and identify which rows change in the result. Explain why the zero score stays zero.