Unexpected BLOB results with MySQL testing NULL variable with IFNULL, COALESCE

耗尽温柔 提交于 2020-06-17 09:48:06

问题


In trying to test whether a variable has been defined, I discovered that the IF, IFNULL, and COALESCE statements return simply BLOB rather than the value I expected when (a) the variable has not been defined or (b) it has been explicitly set to NULL before being assigned a value in the session. I've verified this in MySQL versions 5.7 and 8.0.

SELECT IF(@p IS NULL, 'is null', 'not null'); # 'is null' 
SELECT IF(@p IS NULL, 'is null', @p); # BLOB
SELECT IFNULL(@p, 'is null'); # BLOB
SELECT COALESCE(@p, 'is null'); # BLOB

The first statement acts as I expected, but the others return BLOB rather than 'is null'. The behavior is the same if preceded by SET @p = NULL.

On the other hand, if you do any of these, the above statements will all return 'is null', that is, they act as expected with a null value.

  1. SET @p = NULL + 1 rather than SET @p = NULL before testing.
  2. SET @p = 5; SET @p = NULL; That is, first set a non-null value, then set to null
  3. SELECT COALESCE(@p+1, 'is null') # use expression @p+1 instead of @p.

Presumably, these three somehow set a type for NULL. In any case, an undefined variable or variable only defined as NULL have a different kind of NULL than those with a history of typing (?).

What is the underlying principle that explains this behavior? Is it simply an untyped NULL acts differently than a typed NULL, and those statements don't work with untyped ones?

Note: I know that that a workaround for this in a procedure, in order to detect undefined variables, can be

IF @p IS NULL
    SET @p = default_value
END IF;

and it looks as if I can also use COALESCE(@p+1,default_value). But I'm interested in the explanation for why this is needed. Thanks.

来源:https://stackoverflow.com/questions/62413075/unexpected-blob-results-with-mysql-testing-null-variable-with-ifnull-coalesce

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!