Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange casting behavior in mysql

Here is the code

mysql> SELECT id FROM tbl WHERE id = '1h';
+----+
| id |
+----+
|  1 |
+----+
1 row in set

There is indeed a field with id 1 (but not '1h').
Here is an extraction from MySQL docs: http://dev.mysql.com/doc/refman/5.1/en/type-conversion.html

mysql> SELECT 1 > '6x';
    -> 0
mysql> SELECT 7 > '6x';
    -> 1

So this bug is documented, so to say. The question is what's the reason for such behavior and how to correct it to make this not cast strings with char symbols? I can cast all field values like

mysql> SELECT id FROM tbl WHERE cast(`id`, BINARY) = '1h';

but i don't like this variant too much

like image 531
kos Avatar asked May 12 '26 07:05

kos


1 Answers

This is not a bug.

The solution is not to query on numeric columns using a string value for your condition.

Never rely on implicit type casting.

like image 182
kapa Avatar answered May 14 '26 22:05

kapa