Index on (a,b) vs. (b,a)?

submited by
Style Pass
2024-10-30 12:30:13

Whenever you are considering creation of multicolumn index, there is a question what should be the order of columns in this index. I'll try to analyze various cases of this situation.

First, let's consider that you want to use inequality operators (<, >, <= or &gr;=), and you're using both columns in your query. In this case, you can generally assume both conditions use index.

Of course one can say – OK, you used equality for very selective, and inequality for not really selective column. What would happen if the conditions were swapped?

This shows, in my opinion that in mixed cases (one field using =, and the other some inequality), it's better to have index first on field used for equality.

Which leaves us with relatively simple case – what about case where we have both columns compared using equality, just their selectivity is widely different.

(No, I didn't edit the results – I made script which called both explains 3 times in a row, and stored output of last one)

Leave a Comment