Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use composite indexes?

Tags:

sql

database

What are the general rules in regards to using composite indexes? When should you use them, and when should you avoid them?

like image 762
Alex Avatar asked Jun 01 '09 06:06

Alex


People also ask

What is composite index used for?

A composite index is a statistical tool that groups together many different equities, securities, or indexes in order to create a representation of overall market or sector performance. Composite indexes are used to conduct investment analyses, measure economic trends, and forecast market activity.

What is the strength of using a composite index?

A composite index provides opportunities for index covering. If queries provide search arguments on each of the keys, the composite index requires fewer I/Os than the same query using an index on any single attribute. A composite index is a good way to enforce the uniqueness of multiple attributes.


2 Answers

Composite indexes are useful when your SELECT queries use those columns frequently as criteria in your WHERE clauses. It improves retrieval speed. You should avoid them if they are not necessary.

This article provides some really good information.

like image 197
Jose Basilio Avatar answered Oct 21 '22 13:10

Jose Basilio


A query that selects only a few fields can run completely on an index. For example, if you have an index on (OrderId) this query would require a table lookup:

select Status from Orders where OrderId = 42

But if you add a composite index on (OrderId,Status) the engine can retrieve all information it needs from the index.

A sort on multiple columns can benefit from a composite index. For example, an index on (LastName, FirstName) would benefit this query:

select * from Orders order by LastName, FirsName

Sometimes you have a unique constrant on multiple columns. Say for example that you restart order numbers every day. Then OrderNumber is not unique, but (OrderNumber, OrderDayOfYear) is. You can enforce that with a unique composite index.

I'm sure there are many more uses for a composite index, just listing a few examples.

like image 34
Andomar Avatar answered Oct 21 '22 13:10

Andomar