Back to blog
Jun 2020·1 min readAI-translated

Returning MySQL NULL as 0

#coalesce#done#mysql#null#sql

For a small project I had to sum the values of a column in MySQL and sort by the summed values. Something like

SELECT ITEMS.id, SUM(VOTES.modificator) AS score
FROM items ITEMS
LEFT JOIN votes VOTES ON ITEMS.id = VOTES.item
GROUP BY ITEMS.id
ORDER BY score DESC

But: oh shit. If the votes table has no entry to join, the arithmetic function returns "null". But we want to sort by the result of that function. And what value does null have? In my case, actually 0. So we replace null with 0, like this:

SELECT ITEMS.id, COALESCE(SUM(VOTES.modificator), 0) AS score
FROM items ITEMS
LEFT JOIN votes VOTES ON ITEMS.id = VOTES.item
GROUP BY ITEMS.id
ORDER BY score DESC

What exactly does COALESCE do? Definitely more than mindless "converting". From any number of parameters, COALESCE returns the first one that contains a value (that is, is not null).

COALESCE(NULL, NULL, 'Hello', NULL, 'Elephant')

therefore returns "Hello".

In our case COALESCE returns the sum of VOTES.modificator, unless the "value" (deliberately in quotes, since NULL is of course exactly NOT a value) is null. Then we get 0 back and effectively replace the result of the arithmetic function.

NewerValidating Email AddressesOlderAlphaGo