Question

I have a MySQL table that has, among other attributes, a timestamp, a type and a user_id.
All of them are searchable and/or sortable.
Is it better to create an index for each one, or create a single compound index with all three, or both?

Was it helpful?

Solution

Pablo's answer is correct, but maybe you'll fail to realize that a compound index might be justified.

You can have multiple indexes and having idx1(tstamp, user_id) does not exclude you from having indx2(tstamp, type) or idx1reverse(user_id, tstamp) and so on...

Compound indexes are most useful when they cover all of the conditions in your query, so the index you propose will be most useful for

SELECT * FROM my_table WHERE tstamp = @ts1 AND user_id = @uid AND type = @type

If you want to improve performance of such queries you can consider adding a composite index.

The downside of the indexes is that it slows down all update operations. However, most general applications do many more selects then updates (both in terms transactions i.e. number of statements and especially in terms of of records affected/retrieved) and at the same time are much more tolerant of slower updates (users mostly judge the speed of the system not by the time it is necessary to update a record, but by the time necessary to retrieve records; again YMMV and there are applications that don't play by such rules).

The best would be if you had some way to test the database performance in terms of typical workloads (create some typical SQL scripts; independent and repeatable, or create unit tests at the application level) and then you can objectively tune your database.

EDIT Also realize that indexes can be added and dropped without affecting the system in terms of functionality. Therefore, you can tune your indexes later, during actual usage of the system - and normally you would collect and profile the slow SQL queries looking for conditions that could benefit from adding indexes.

OTHER TIPS

If you are going to perform searches on those fields separately, you will probably need separate indexes to make your queries run faster.

If you have an index like this:

mysql> create index my_idx on my_table(tstamp, user_id, type);

And you query is:

mysql> select * from my_table where type = 'A';

Then my_idx won't be that helpful for your query and MySQL will end up doing a full table scan to resolve it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top