Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sql single index or multiple index

Let's say I have the Products table.

On my UI, I allow the user to search by name, description, code The user can only search on criteria.

Should I create an index for each criteria : name, description, code or create ONE single index for all 3?

What will make you choose one versus the other?

like image 453
pdiddy Avatar asked Sep 17 '10 18:09

pdiddy


People also ask

Is it good to have multiple indexes on a table in SQL?

Basically it helps your data insert at the end of the index and not cause lots of disk IO and Page splits. Secondly, if you are creating other indexes on your data and they are constructed cleverly they will be reused.

Is it a good idea to have multiple indexes?

Yes you can have too many indexes as they do take extra time to insert and update and delete records, but no more than one is not dangerous, it is a requirement to have a system that performs well.

Can a SQL query use multiple indexes?

Yes, but not with the indexes you've chosen. And that's without having to use multiple index hints.

What is difference between composite index and single index?

Like a single index, a composite index is also a data structure of records sorted on something. But unlike a single index, that something is not a field, but a concatenation of multiple fields. position = 'Top'; will have improved retrieval time, because the composite index is sorted by class-position .


2 Answers

Whenever you build an index on multiple columns, say create index .. on T(A, B, C), the index can only be used if the leftmost columns are specified. If you search on column A, the index can be used. If you search on columns A and B then the index can be used. If you search on columns A and B and C then the index can be used. But the index will not be used if you search on column B only, or on column C only or on columns B and C only.

So if you want to search on Product or on Description or on Code you need separate indexes on each. If you want to search for a term in any of the three columns then most likely you need a Full Text search. Same goes for Description, is very unlikely you want a normal index on it, most likely you need a Full Text index on it.

like image 162
Remus Rusanu Avatar answered Oct 06 '22 00:10

Remus Rusanu


You need an index for each. One index for all three will only benefit searches involving the first criterion in the index, or that in combination with the second, etc.

like image 32
Andrew Avatar answered Oct 06 '22 01:10

Andrew