I have a simple table “t1” that contains:
word VARCHAR(16)
id INT
importance SMALLINT
word and id are unique together, but neither is unique alone.
I added a UNIQUE INDEX(word, id)
My query looks something like this:
SELECT id FROM t1 WHERE word = "something" ORDER BY importance DESC
But it takes 0.0002 seconds to execute say:
SELECT id FROM t1 WHERE word = "something"
But takes as much as 0.15s to execute the ORDER BY importance DESC.
My question is, how can I index/reorder my table so it’s organized firstly by word, then by importance without having to do the sorting on the fly?
Can I just reorder the static data so it’s sorted by word, importance DESC by default?
To speed up your query, add an index on
(word, importance DESC, id).You can have more than one index on a table so you don’t need to remove your existing index if you don’t want to.