[Solved] Improve performance of a join between a varchar field and a substring applied to another field

EverSQL Database Performance Knowledge Base

Improve performance of a join between a varchar field and a substring applied to another field

Database type:

I have a MySQL varchar field with values like these:

'00007_1'
'00016_1'
'00016_2'
'00231_1'
'00326_3'

I'm looking for the best way to put this field in join with another table with a varchar field with values like these (I list those that match previous):

'7'
'16'
'16'
'231'
'326'

This is how I've made:

SELECT *
FROM   R
INNER JOIN RC ON Trim(leading '0' from Substring(R.N_DEN,1,instr(R.N_DEN,'_')-1)) = RC.N_DEN

Anybody knows if there is a quicker and better performace solution?

How to optimize this SQL query?

The following recommendations will help you in your SQL tuning process.
You'll find 3 sections below:

  1. Description of the steps you can take to speed up the query.
  2. The optimal indexes for this query, which you can copy and create in your database.
  3. An automatically re-written query you can copy and execute in your database.
The optimization process and recommendations:
  1. Avoid Selecting Unnecessary Columns (query line: 2): Avoid selecting all columns with the '*' wildcard, unless you intend to use them all. Selecting redundant columns may result in unnecessary performance degradation.
  2. Create Optimal Indexes (modified query below): The recommended indexes are an integral part of this optimization effort and should be created before testing the execution duration of the optimized query.
Optimal indexes for this query:
ALTER TABLE `RC` ADD INDEX `rc_idx_n_den` (`N_DEN`);
The optimized query:
SELECT
        * 
    FROM
        R 
    INNER JOIN
        RC 
            ON Trim(leading '0' 
    from
        Substring(R.N_DEN,
        1,
        instr(R.N_DEN,
        '_') - 1)) = RC.N_DEN

Related Articles



* original question posted on StackOverflow here.