I have a test table with schema like this:
CREATE TABLE `indextest` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(10) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `idx_name` (`name`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=latin1
and here are the rows in the table:
mysql [localhost] {msandbox} (test) > select * from indextest;
+----+--------+
| id | name |
+----+--------+
| 3 | 111222 |
| 1 | hello |
| 2 | world |
| 4 | wow |
+----+--------+
4 rows in set (0.00 sec)
when I query the table against the name column with a string, it looks good:
mysql [localhost] {msandbox} (test) > explain select * from indextest where name='111222'\G
*************************** 1. row ***************************
id: 1
select_type: SIMPLE
table: indextest
type: ref
possible_keys: idx_name
key: idx_name
key_len: 13
ref: const
rows: 1
Extra: Using where; Using index
1 row in set (0.00 sec)
But if I use a numeric as the query parameter, explain shows that the query optimizer is doing index scan:
mysql [localhost] {msandbox} (test) > explain select * from indextest where name=111222\G
*************************** 1. row ***************************
id: 1
select_type: SIMPLE
table: indextest
type: index
possible_keys: idx_name
key: idx_name
key_len: 13
ref: NULL
rows: 4
Extra: Using where; Using index
1 row in set (0.00 sec)
and under some other conditions (found in online slow queries), the query optimizer even suggests doing similar queries with table scan.
I don't understand why it behaves like this but not just raises error or converts the numeric to a string automatically.