In my table I have two closely related columns A and B. What possible considerations shall I made to decide whether to create:
How does this change if I:
where A = 5 and B = 10
(and never like where A = 5
),where A > 3 and A < 10 and B > 12 and B < 20
,order by (A, B)
,group by (A, B)
?Note: I intentionally haven't provided more details about my particular case as I want a general answer that will also serve to others. I use mysql, but if you give more general answer that covers SQL in general that would be great.
Ok, when you have an index(A,B), MySQL can also use it as an index(A). Declaring AB and A has no sense. Declaring AB and B does, however
So you have these choices:
If you always use both columns (or the first one of the index) in your WHERE
/ GROUP BY
/ ORDER BY
you should use index(A,B)
.
The second one in the index (in this case B) cannot be used separately, but the first one can (only the first one in any case).
So if you never use B on its own, then index(A,B)
should be sufficient. If you never use A on its own, but you do use B, then do index(B,A)
. If you do use both separately, but mostly together, then add the other index separately.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With