12

Does MySQL automatically casting\converting the string to numeric value?
How does that conversion works?

  • '1234'=1234 ?
  • '1abc' = 1 ?
  • 'text' = 1 ?

Given that units.id is of bigint type, how this query will be interpreted?

SELECT table.* 
FROM table 
WHERE id='text'
yossi
  • 3,090
  • 7
  • 45
  • 65
  • 1
    [yes](http://stackoverflow.com/questions/14411380/what-is-the-meaning-of-select/14411466#14411466) – Grijesh Chauhan Feb 13 '14 at 18:08
  • Note that this is another good reason to validate any user-supplied parameters before using them in a query (even when using prepared statements). – alexw Nov 29 '20 at 16:26

3 Answers3

13

The answers to your first three questions are: yes, yes, and no.

When the string 'text' is converted to a number, it becomes the value 0.

The documentation that describes type conversion is here.

For your query:

SELECT table.* 
FROM table 
WHERE id='text';

The rule is captured by this excerpt from the documentation:

In all other cases, the arguments are compared as floating-point (real) numbers.

In other words, this is actually equivalent to:

WHERE id = 0.0
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
5

MySQL by default treats 1 and '1' the same however you can change that by setting the MySQL behavior to Strict mode.

set @@GLOBAL.sql_mode  = "STRICT_ALL_TABLES";
set @@SESSION.sql_mode = "STRICT_ALL_TABLES";

or you can set these variables in your my.cnf file to be permanent in sql_mode = ''. This way MySQL will throw an error if an incorrect type is used. Read http://dev.mysql.com/doc/refman/5.0/en/server-sql-mode.html for more details

Sam
  • 2,761
  • 3
  • 19
  • 30
1

Like any DBMS, it does the implicit conversion.

For other type, according to the MySQL documentation, you have to use the convert/cast function http://dev.mysql.com/doc/refman/5.0/en/cast-functions.html

Here is an example from SO: Convert text into number in MySQL query

Community
  • 1
  • 1
Elfentech
  • 747
  • 5
  • 10
  • 3
    Postgres does not do implicit conversion when doing SELECT, and even when it does '1abc' != 1, so "any" is too broad when considering OP – Victor Moroz Mar 14 '16 at 15:39