I have a table that contains several thousand rows, having a Varchar column that contains numbers. Despite discussing why this column is not a numeric type then, selecting rows from that table showed a strange behavior.
Although there is an index on that column, using numeric strings to find a row is MUCH faster (0.01 secs) than using Ints (0.54 secs). What is the reason for this? It seems not to be able to cast and use the value for the index...
Am I overlooking something? It looks like it is not casting the Int to use it for the index? Do I have to give hints on index usage, or is there a database switch to accomplish this? Or if I misunderstand the Explain output, why is it so much slower then?
Table layout to show an example:
CREATE TABLE `example` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`stuff` varchar(45) NOT NULL,
PRIMARY KEY (`id`),
KEY `idx_stuff` (`stuff`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Here it is using the String for the index:
explain select * from example where stuff='200';
----+-------------+---------+------+---------------+-----------+---------+-------+------+--------------------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+---------+------+---------------+-----------+---------+-------+------+--------------------------+
| 1 | SIMPLE | example | ref | idx_stuff | idx_stuff | 137 | const | 1 | Using where; Using index |
+----+-------------+---------+------+---------------+-----------+---------+-------+------+--------------------------+
Here it looks like it does not cast the Int to a String to use for looking up the index:
explain select * from example where stuff=200;
+----+-------------+---------+-------+---------------+-----------+---------+------+------+--------------------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+---------+-------+---------------+-----------+---------+------+------+--------------------------+
| 1 | SIMPLE | example | index | idx_stuff | idx_stuff | 137 | NULL | 2 | Using where; Using index |
+----+-------------+---------+-------+---------------+-----------+---------+------+------+--------------------------+
varchar
searching as a string has to be faster. – Dizon