[Solved] How to speed up single query with large dataset sql server and php

How to optimize this SQL query?

In case you have your own slow SQL query, you can optimize it automatically here.

For the query above, the following recommendations will be helpful as part of the 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 Calling Functions With Indexed Columns (query line: 20): When a function is used directly on an indexed column, the database's optimizer won’t be able to use the index. For example, if the column `id` is indexed, the index won’t be used as it’s wrapped with the function `LOWER`. If you can’t find an alternative condition that won’t use a function call, a possible solution is to store the required value in a new indexed column.
  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:
CREATE INDEX example_table2_idx_id ON dbo.Example_Table2 (id);
The optimized query:
SELECT
        LOWER(CONVERT(VARCHAR(32),
        CONVERT(VARBINARY(32),
        r.id),
        2)) AS id,
        r.id AS respondentid,
        'new' AS qtype,
        r.email,
        r.language,
        'Y' AS is_online,
        r.createdDate AS time,
        r.createdDate AS date_sent,
        r.state AS state,
        r.sourceID AS sourceid,
        req.id 
    FROM
        [Example_Server1].[Example_Database1].[dbo].Example_Table1 AS r 
    LEFT JOIN
        [Example_Server2].[Example_Database2].[dbo].Example_Table2 req 
            ON LOWER(CONVERT(VARCHAR(32),
        CONVERT(VARBINARY(32),
        r.id),
        2)) = req.id 
    WHERE
        req.id IS NULL

Related Articles



* original question posted on StackOverflow here.