[Solved] Heavy cost (99%) for insert in query execution plan

EverSQL Database Performance Knowledge Base

Heavy cost (99%) for insert in query execution plan

I have a query as follows:

SELECT c.irn, 
       pLog.policingname, 
       ce.* 
INTO   #caselist 
FROM   employeereminder_ilog ce 
       JOIN cases c 
         ON ce.caseid = c.caseid 
       JOIN policinglog pLog 
         ON ( ce.logdatetimestamp BETWEEN 
              pLog.startdatetime AND pLog.finishdatetime ) 
WHERE  ce.logdatetimestamp BETWEEN @start_pre AND @end_pre 

employeereminder_iLOG is a pretty huge table, around 32M rows. POLICINGLOG has around 50 rows. CASES around 0.5m rows. @start_pre and @end_pre are predefined variabled around 30 minutes apart.

This query took around 30 minutes to run, and returns around 600 results.

I was trying to find way to speed up the query by looking at the execution plan. I couldn't work out why however the insert was taking up 99% of the query, as opposed to the select from employeereminder_iLOG .

enter image description here

So, my questions are:

  1. Why is the cost coming from the insert, and not the select from employeereminder_iLOG.
  2. Is it possible to speed up this query?

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: 4): 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 `cases` ADD INDEX `cases_idx_caseid` (`caseid`);
ALTER TABLE `employeereminder_ilog` ADD INDEX `employeereminder_i_idx_logdatetimestamp` (`logdatetimestamp`);
The optimized query:
SELECT
        c.irn,
        pLog.policingname,
        ce.* INTO #caselist 
    FROM
        employeereminder_ilog ce 
    JOIN
        cases c 
            ON ce.caseid = c.caseid 
    JOIN
        policinglog pLog 
            ON (
                ce.logdatetimestamp BETWEEN pLog.startdatetime AND pLog.finishdatetime
            ) 
    WHERE
        ce.logdatetimestamp BETWEEN @start_pre AND @end_pre

Related Articles



* original question posted on StackOverflow here.