Reputation: 9496
I am trying to understand indexing in RDBMS, and I am having hard time understanding Index Merge Intersection optimization while executing SQL query. Let's take this query as example
SELECT * FROM innodb_table
WHERE primary_key < 10 AND key_col1 = 20;
Suppose we have two indices, one for each key column. How does using index merge benefit us here?
For e.g. we can use index of primary_key column to do range scan, and then do a linear scan of intermediate results to get the expected output.
How can Index Merge give us better performance?
Upvotes: 0
Views: 1404
Reputation: 142528
For WHERE primary_key < 10 AND key_col1 = 20
, provide
INDEX(key_col1, primary_key)
in that order. Discussion:
=
columns first in the index; one 'range' last.How would merge work?
primary_key < 10
key_col1 = 20
SELECT *
).How would the composite key work?
key_col1 = 20
; it will have the smallest primary_key
.SELECT *
using the PK.10
.Without the composite index, probably this is what the optimizer will do:
key_col1 = 20
is false; else deliver rowprimary_key < 10
EXPLAIN SELECT ...
will tell you which method it chose.
As for index merge union...
OR
.UNION
instead of OR
is a better option.Upvotes: 0
Reputation: 98433
What makes you think it gives better performance? Sometimes it may; it would depend a lot on the cardinality of the indexes and particular values/ranges being searched.
In practice, it often means you should pick which index will perform better and add an index hint.
Upvotes: 0