Asked 3 years ago
29 Jul 2021
Views 417
Buddy

Buddy posted

mysql: compare integers with strings and return true

mysql: compare integers with strings and return true
Rasi

Rasi
answered Feb 27 '23 00:00

In MySQL, when you compare integers with strings, MySQL will attempt to convert the string to an integer before doing the comparison. If the string cannot be converted to an integer, it will be treated as 0.

Here's an example:


SELECT * FROM my_table WHERE some_column = 123;

In this query, we are comparing the some_column column with the integer value 123. If the values in some_column are integers, the comparison will work as expected. However, if some of the values in some_column are strings, MySQL will attempt to convert them to integers before doing the comparison.

For example, if some_column contains the following values:


123
456
'789'
'abc'

Then the query will return the first three rows, because the string '789' will be converted to the integer 789, and the string 'abc' will be treated as 0.

If you want to avoid this behavior, you can use the CAST() function to convert the string to an integer explicitly:

SELECT * FROM my_table WHERE some_column = CAST('123' AS UNSIGNED);


In this query, we are using the CAST() function to convert the string '123' to an unsigned integer before doing the comparison. This will ensure that MySQL does not convert any of the other values in some_column to integers, and will only match rows where some_column is exactly equal to the integer value 123.
Post Answer