[Solved] Rank statement is causing query to run very 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. 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.
  2. Remove Redundant Left Joins (modified query below): Redundant LEFT JOINs (e.g. `CLARITY_DEP`) were detected in the query. Removing them will result in a performance improvement. In some cases, JOINs become redundant after an optimization is applied, such as when converting OR conditions to a UNION clause.
Optimal indexes for this query:
ALTER TABLE `IP_FLWSHT_MEAS` ADD INDEX `ip_meas_idx_fsd_id` (`FSD_ID`);
ALTER TABLE `PATIENT_3` ADD INDEX `patient_3_idx_pat_id` (`PAT_ID`);
ALTER TABLE `PAT_ENC_HSP` ADD INDEX `pat_hsp_idx_inpatient_id` (`INPATIENT_DATA_ID`);
The optimized query:
SELECT
        REC.INPATIENT_DATA_ID,
        RANK() OVER (PARTITION 
    BY
        PATS.PAT_ENC_CSN_ID,
        MEAS.FLO_MEAS_ID 
    ORDER BY
        MEAS.RECORDED_TIME) 'VITALS_RANK',
        MEAS.RECORDED_TIME,
        PATS.PAT_ENC_CSN_ID,
        PATS.PAT_ID,
        PATS.CONTACT_DATE,
        MEAS.FLO_MEAS_ID,
        PATS.DEPARTMENT_ID,
        PAT.IS_TEST_PAT_YN,
        PATS.HOSP_DISCH_TIME,
        PATS.HOSP_ADMSN_TIME 
    FROM
        CLARITY.DBO.IP_FLWSHT_REC REC 
    LEFT OUTER JOIN
        CLARITY.DBO.PAT_ENC_HSP PATS 
            ON PATS.INPATIENT_DATA_ID = REC.INPATIENT_DATA_ID 
    LEFT OUTER JOIN
        CLARITY.DBO.PATIENT_3 PAT 
            ON PAT.PAT_ID = PATS.PAT_ID 
    LEFT OUTER JOIN
        CLARITY.DBO.IP_FLWSHT_MEAS MEAS 
            ON REC.FSD_ID = MEAS.FSD_ID

Related Articles



* original question posted on StackOverflow here.