I have a table which will be about 2 – 5 million rows on average. It has a primary key/index called ‘instruction_id’ and another indexed field called ‘mode’. now ‘instruction_id’ is of course unique since it is the primary key but ‘mode’ will only be one of 3 different values. The query I run all the time is
SELECT * FROM tablename WHERE mode = 'value1' ORDER BY instruction_id LIMIT 50
This currently takes about 25 sec ( > 1 sec is unacceptably long) but there are only 600K rows right now so it will get worse as the table grows. Would indexing in a different way help? If I index instruction_id and mode together will that make a difference? If I somehow am able to naturally order the table by instruction_id so I don’t have to ask for the order by would be another way around this but I don’t know how to do that… Any help would be great.
You should try index on (mode, instruction_id), in that order.
The reasoning behind that index is that it creates an index like this
If you search for mode B the sql server can search the index with a binary search on mode until it finds the first B, then it can simply output the next
nrows. This would be really fast, about 22 compares for 4M rows.Always use
ORDER BYif you expect the result to be ordered, regardless of how the data is stored. The query engine might choose a query plan that output the rows in a different order than the order of the PK (maybe not in such simple cases as this, but in general).