Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Order of index on multiple columns

Tags:

Just a simple question, but does the order of your index matter when it spans over multiple columns?

For example, taking the query:

SELECT * FROM my_table WHERE (column_1 = 1 AND column_2 = 2)

If I want to add an index for a query like this, does it matter if my index is created like this:

CREATE INDEX my_index
ON my_table (column_1, column_2)

Or like this:

CREATE INDEX my_index
ON my_table (column_2, column_1)

Thanks for the help!

like image 234
japancheese Avatar asked Dec 03 '09 15:12

japancheese


2 Answers

In the example you give, the column order does not matter.

It would matter if you order on a column; an index on (col1,col2) can be used for ORDER BY col1, col2 but not for ORDER BY col2, col1.

For WHERE clauses, an index on (col1, col2) works for WHERE col1 = 1 AND col2 = 1. It also works for WHERE col1 = 1. But it can't help with WHERE col2 = 1.

like image 122
Andomar Avatar answered Oct 07 '22 13:10

Andomar


This shoudl give you a good idea

SQL Server Clustered Index - Order of Index Question

There are many more like this on SO.

like image 33
Adriaan Stander Avatar answered Oct 07 '22 14:10

Adriaan Stander