Replacing Null with COALESCE
COALESCE selects the first non-null argument. Use it when the replacement reflects the output's declared semantics.
- Source
- Anbloq
- Language
- English
- Created
- Updated
- Chapters
- 4
- Reading time
- 1 min
In this article4 chapters
Trace a label fallback
A row may have a short label, or the query can show its full label when short is null. An empty short label remains present. See unset and empty values.
Keep stored information distinct
Converting missing scores to zero before taking a mean changes the population. Replacing a displayed empty total can be a separate choice. COUNT of values identifies present observations.[1]
Substitute only when the fallback is justified
An expense report can display null sums for missing measurements, or zero for days known to have no bills. COALESCE picks the first non-null expression. A stored zero is already present and survives. See missing, empty and zero values.
COALESCE(NULL, 5) → 5
COALESCE(0, 5) → 0
COALESCE(NULL, NULL, 7) → 7
Preserve evidence when absence has a separate meaning
Replacing null in every query can hide incomplete data. A report can carry an accompanying count of present observations. Test a genuinely observed zero and a missing value side by side.