I'm trying to understand a huge performance difference that I'm seeing in equivalent code. Or at least code I think is equivalent.
I have a table with about 10 million records on it. It contains a field, which is indexed defined as: USPatentNum char(8)
If I set a variable withing MySql to a value, it takes over 218 seconds. The exact same query with a string literal takes under 1/4 of a second.
In the code below, the first select statement (with where USPatentNum = @pn;) takes forever, but the second, with the literal value (where USPatentNum = '5288812';) is nearly instant
mysql> select @pn := '5288812'; +------------------+ | @pn := '5288812' | +------------------+ | 5288812 | +------------------+ 1 row in set (0.00 sec) mysql> select patentId, USPatentNum, grantDate from patents where USPatentNum = @pn; +----------+-------------+------------+ | patentId | USPatentNum | grantDate | +----------+-------------+------------+ | 306309 | 5288812 | 1994-02-22 | +----------+-------------+------------+ 1 row in set (3 min 38.17 sec) mysql> select @pn; +---------+ | @pn | +---------+ | 5288812 | +---------+ 1 row in set (0.00 sec) mysql> select patentId, USPatentNum, grantDate from patents where USPatentNum = '5288812'; +----------+-------------+------------+ | patentId | USPatentNum | grantDate | +----------+-------------+------------+ | 306309 | 5288812 | 1994-02-22 | +----------+-------------+------------+ 1 row in set (0.21 sec)
Two questions:
Why is the use of the @pn so much slower? Can I change the select statement so that the performance will be the same?