I have a MySQL database that is exhibiting behavior I would like to understand better. Why can I search for a CHAR value inserted into an INT field? I have a field that is of type INT but it seems to be able to record character values, how is that possible?
I tried to isolate the issue by creating a database with an INT and VARCHAR. I inserted "TEST1" into the INT value but was still able to search for the row using the ID string value. The warning after inserting the string into the ID value is
| Warning | 1366 | Incorrect integer value: 'TEST1' for column 'ID' at row 1 |
but I was still able to search for that value. I would like to understand why this is possible.
mysql> CREATE TABLE test1(ID int, DATA varchar(255));
Query OK, 0 rows affected (0.18 sec)
mysql> INSERT INTO test1(ID,DATA) VALUES('TEST1', 'TEST1');
Query OK, 1 row affected, 1 warning (0.00 sec)
mysql> SELECT * FROM test1 WHERE ID = 'TEST1';
+------+-------+
| ID | DATA |
+------+-------+
| 0 | TEST1 |
+------+-------+
1 row in set, 1 warning (0.00 sec)
The warning after the SELECT is
| Warning | 1366 | Incorrect integer value: 'TEST1' for column 'ID' at row 1 |
but the results is still correct.
I would expect the SELECT above to find 0 results, but that is not the case, why?
ANSWER:
With the help of Asaph's answer below and Pekka's comments the answer seems obvious now.
During the INSERT, MySQL failed to insert the character value into an INT field so it replaced it with 0. The same thing happened during the SELECT so in effect I was doing a SELECT on ID = 0 for any character value I was searching.
mysql> SELECT * FROM test1 WHERE ID = 'SOMETHING_OTHER_THAN_TEST1';
+------+-------+
| ID | DATA |
+------+-------+
| 0 | TEST1 |
+------+-------+
1 row in set, 1 warning (0.00 sec)
That returns the same result as the my initial select since it really is running as
SELECT * FROM test1 WHERE ID = 0;
in the backend.
In any case the best practice seems to be to use sql_mode = 'STRICT_ALL_TABLES' in the MySQL configuration file or the SQL statement itself.
To enable STRICT_ALL_TABLES for all SQL queries on a MySQL server you need to add the following under the [mysqld] header in your my.cnf file which is usually located in /etc/my.cnf
[mysqld]
...
...
...
sql-mode=STRICT_ALL_TABLES