views:

42

answers:

1

I need to select a row from table that has more than 5 millions of rows. It is table of all IP ranges. Every row has columns upperbound and lowerbound. All are bigintegers, and the number is integer representation of IP address.

The select is:

select * 
  from iptocity 
 where lowerbound < 3529167967 
   and upperbound >= 3529167967 
 limit 1;

My problem is

...that the select takes too long time. Without index on an InnoDB table, it takes 20 seconds. If it is on MyISAM then it takes 6 seconds. I need it to be less than 0.1 sec. And I need to be able to handle hundreds of such selects per second.

I tried to create index on InnoDB, on both columns upperbound and lowerbound. But it didn't help, it took even more time, like 40 seconds to select ip. What is wrong? Why did index not help? Does index work only on = operator, and >,< operators can't use indexes? What should I do to make it faster to have less than 0.1 sec selection time?

+2  A: 

Did you create one index on both columns, or two indexes one column each? If only one index, then this could be your problem, make one index for each. Indexes should still work for < and >

Aside from changing indexes around, run:

EXPLAIN
select *
from iptocity
where lowerbound<3529167967
  and upperbound>=3529167967
limit 1;

Same query as you had, just added EXPLAIN and some linebreaks for readability.

The EXPLAIN keyword will make MySQL explain to you how it's running the query, and it will tell you whether indexes are being used or not. For any slow running query, always use explain to try figuring out what's going on.

Slokun
Thx, man. I did index wrong on both columns. Separate index for every column works. I also changed bigint to int and setuped those columns as non Null. Now select is very fast, average 10 milisecods.
@user Glad to know it helped! But an FYI, on SO and related site, when you've found an answer solves your problem, you're supposed to accept it as the correct one by checking the big green check mark next to it.
Slokun