[Solved] SQL: My very short code times out; REGR_SLOPE is being super slow

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 LIKE Searches With Leading Wildcard (query line: 24): The database will not use an index when using like searches with a leading wildcard (e.g. '%WAFERCT%'). Although it's not always a satisfactory solution, please consider using prefix-match LIKE patterns (e.g. 'TERM%').
  2. Avoid Subqueries (query line: 11): We advise against using subqueries as they are not optimized well by the optimizer. Therefore, it's recommended to join a newly created temporary table that holds the data, which also includes the relevant search index.
  3. 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 machine_signal_idx_signal_id_machine_id ON MACHINE_SIGNAL (SIGNAL_ID,MACHINE_ID);
CREATE INDEX tsd_sub_idx_machine_id ON TSD_SUB (MACHINE_SIGNAL_ID);
The optimized query:
SELECT
        DISTINCT q1.MACHINE_ID,
        q1.SIGNAL_ID,
        ROUND(86400000 * (REGR_SLOPE(ts.VALUE,
        ts.EPOCH) OVER (PARTITION 
    BY
        ts.MACHINE_SIGNAL_ID ))) AS RATE,
        q1.LAST_VALUE 
    FROM
        TSD_SUB ts,
        (SELECT
            ms.MACHINE_SIGNAL_ID,
            ms.LAST_TIMESTAMP 
        FROM
            MACHINE_SIGNAL ms 
        WHERE
            (
                ms.MACHINE_ID LIKE 'CV%'
            ) 
            AND (
                ms.SIGNAL_ID = ANY(
                    'WFRCOUNT', 'WFRCNTR'
                ) 
                OR ms.SIGNAL_ID LIKE '%WAFERCT%'
            )) q1 
    WHERE
        ts.MACHINE_SIGNAL_ID = q1.MACHINE_SIGNAL_ID 
        AND ts.EPOCH > (
            q1.LAST_TIMESTAMP - 604800000
        )

Related Articles



* original question posted on StackOverflow here.