samedi 19 décembre 2020

Why MySQL IF(0 = 'foo', 1, 2) resolves in 1, i.e. string equals 0 [duplicate]

This must have been documented and asked before, but I can't seem to find any sensible information about it.

Short version/actual problem

When creating a MySQL procedure the following resolves as true:

IF(0 = 'foo', 1, 2) /* resolves in 1 */

Though the string 'foo' isn't equal to 0.

The following query resolves as not true:

IF(1 = 'foo', 1, 2) /* resolves in 2 */

Which makes sense, since the string 'foo' isn't equal to 1.

How come might this be?

Practical use case

I have a column which allows null values. Sometimes this column should hold the value 0. Due to the way data comes in from the API, empty string should write NULL in the column and 0 should write 0.

The procedure that handles the data uses the following IF functions to handle these cases:

IF(variable="", NULL, variable)

If the variable = 0 the above produces NULL as opposed to the expected 0.

Aucun commentaire:

Enregistrer un commentaire