views:

11

answers:

1

A quick question. I have a simple table with this structure:

USERS_TABLE = {id}, name, number_field_1, number_field_2, number_field_3, number_field_4, number_field_5

Sorting is a major feature, one field at a time at the moment. Table can have up to 50 million records. Most selects are done using the "id" field, which is the primary key and it's indexed.

A sample query:

SELECT * FROM USERS_TABLE WHERE id=10 ORDER BY number_field_1 DESC LIMIT 100;

The question:

Do I create separate indexes for each "number_field_*" to optimize ORDER BY statements, or is there a better way to optimize? Thanks

+1  A: 

There's no silver bullet here, you will have to test this for your data and your queries.

If all your queries (e.g. WHERE id=10) returns few rows, it might not be worth indexing the order by columns. On the other hand, if they return a lot of rows, it might help greatly.

If you always order by atleast one of the fields, consider creating an index on that column, or a compound index on some of these columns - keep in mind that if you have a compound index on (num_field_1,num_field_2) and you order only by num_field_2 , that index will not be used. You have to include the leftmost fields of the index to make use of it.

On the other hand, you seem to have a lot of different fields you order by, the drawback of creating an index on each an every one of them is your indexes will be much larger, and your inserts/deletes/updates might start to get slower.

Basically - there is no shortcut. You'll have to play around with which indexes works best for your queries and tune accordingly, while carefully analyzing your queries with EXPLAIN

nos
Thanks for the answer. I am not sure if sorting 50k records returned counts as a lot or a few. I think a lot. I will definitely use the EXPLAIN function to check.
Amer
50k would probably count as a lot.
nos