Creating an index on a timestamp to optimize query

DanielGibbs picture DanielGibbs · Jan 31, 2012 · Viewed 55k times · Source

I have a query of the following form:

SELECT * FROM MyTable WHERE Timestamp > [SomeTime] AND Timestamp < [SomeOtherTime]

I would like to optimize this query, and I am thinking about putting an index on timestamp, but am not sure if this would help. Ideally I would like to make timestamp a clustered index, but MySQL does not support clustered indexes, except for primary keys.

  • MyTable has 4 million+ rows.
  • Timestamp is actually of type INT.
  • Once a row has been inserted, it is never changed.
  • The number of rows with any given Timestamp is on average about 20, but could be as high as 200.
  • Newly inserted rows have a Timestamp that is greater than most of the existing rows, but could be less than some of the more recent rows.

Would an index on Timestamp help me to optimize this query?

Answer

Chris Nash picture Chris Nash · Jan 31, 2012

No question about it. Without the index, your query has to look at every row in the table. With the index, the query will be pretty much instantaneous as far as locating the right rows goes. The price you'll pay is a slight performance decrease in inserts; but that really will be slight.