Rob
Rob

Reputation: 71

Does adding an index on the column you are selecting speed up the query?

I have a fairly common setup, I have a table of tags and record pairs. Querying it is slow so adding an index to the column of the tag I am querying helps speed it up.

tag  | site
123  | 456
789  | 101

My question is whether it is beneficial to add an index on both these columns as one index. It will never be selected by the site, so is there any benefit to doing this? I also cannot guarantee that each pairing is unique without making some changes but if I did would this help with performance?

A typical query might look like this:

SELECT site, tag FROM sitetags WHERE tag ='123' OR tag = '789'

Upvotes: 4

Views: 585

Answers (2)

Zamrony P. Juhara
Zamrony P. Juhara

Reputation: 5262

If you always search by tag then you only need to index tag column.

Adding column to index when it is not used, introduce unneeded overhead when you insert or update record and also consume more storages.

But composite index (tag, site) may give additional optimization as MySQL only need to read index to satify your query (EXPLAIN usually marks this optimization as using index).

If your operation is mostly read rather than write, then using composite index may not be a bad idea.

It will be better if tag column has high cardinality, meaning that there is high chance that their values are different between each rows.

But I suggest you consult EXPLAIN output first.

Upvotes: 5

sagi
sagi

Reputation: 40471

If these is the only columns that exist in the table, then the answer is no, it won't speed up your query because it will have to process the entire row anyways.

If not, then yes, adding an index on a selected column can speed up the query, because the optimizer will be able to select the value without actually processing the entire row.

Normally, you should index only the columns you filter by. I advise to add an index on a selected column only if you actually use this format of select a lot, if not , the disadvantages (such as slow inserts) can overcome the benefits .

Note: Your typical query should actually look like this:

WHERE tag IN('123','789')

Upvotes: 0

Related Questions