I am trying to join two tables where there is a datatype mismatch between the join columns. Index is not getting picked up even after an explicit conversion (or after forcing the index). What could be the reason?
create table table_a (
table_a_col1 decimal(18)
);
create table table_b (
rec_id decimal(18) ,
table_b_col2 varchar(18)
);
create index table_b_col2_ndx on table_b (table_b_col2);
insert into table_a values (1);
insert into table_a values (2);
insert into table_b values (1,'1');
insert into table_b values (2,'2');
insert into table_b values (4,'S');
commit;
Plan without doing any conversion
explain
select *
from table_a
left join table_b
on (table_b_col2 = table_a_col1)
where table_a_col1 = 2;
|id |select_type|table |type|possible_keys |key|key_len|ref|rows|Extra |
|---|-----------|-------|----|----------------|---|-------|---|----|----------------------------------------------|
|1 |SIMPLE |table_a|ALL | | | | |2 |Using where |
|1 |SIMPLE |table_b|ALL |table_b_col2_ndx| | | |3 |Range checked for each record (index map: 0x1)|
Plan after explicit datatype conversion
explain
select *
from table_a
left join table_b
on (table_b_col2 = cast(table_a_col1 as character))
where table_a_col1 = 2;
|id |select_type|table |type|possible_keys|key|key_len|ref|rows|Extra |
|---|-----------|-------|----|-------------|---|-------|---|----|-----------------------------------------------|
|1 |SIMPLE |table_a|ALL | | | | |2 |Using where |
|1 |SIMPLE |table_b|ALL | | | | |3 |Using where; Using join buffer (flat, BNL join)|
Plan after forcing the index
explain
select *
from table_a
left join table_b force index (table_b_col2_ndx)
on (table_b_col2 = cast(table_a_col1 as character))
where table_a_col1 = 2;
|id |select_type|table |type|possible_keys|key|key_len|ref|rows|Extra |
|---|-----------|-------|----|-------------|---|-------|---|----|-----------------------------------------------|
|1 |SIMPLE |table_a|ALL | | | | |2 |Using where |
|1 |SIMPLE |table_b|ALL | | | | |3 |Using where; Using join buffer (flat, BNL join)|
select version() ;
|version() |
|------------------|
|10.2.9-MariaDB-log|