[Solved] Postgres Hash Join speed

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 OR Conditions By Using UNION (modified query below): In mosts cases, filtering using the OR operator cannot be applied using indexes. A more optimized alternative will be to split the query to two parts combined with a UNION clause, while each query holds one part of the original OR condition.
  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.
  3. Use UNION ALL instead of UNION (query line: 50): Always use UNION ALL unless you need to eliminate duplicate records. By using UNION ALL, you'll avoid the expensive distinct operation the database applies when using a UNION clause.
  4. Use UNION Over COALESCE On Indexable Columns (query line: 30): When a function is used directly on an indexed column, the database's optimizer won’t be able to use an index for that filtering condition. In the case of the function COALESCE, it can be replaced with conditions that reflect the same logic. Splitting them to different queries which are combined with a UNION, will allow optimal index usage.
Optimal indexes for this query:
CREATE INDEX devices_idx_id ON "devices" ("id");
CREATE INDEX patient_devices_idx_unassignme_device_id_issuance ON "patient_devices" ("unassignment_datetime","device_id","issuance_datetime");
CREATE INDEX patient_devices_idx_device_id_issuance_dateti ON "patient_devices" ("device_id","issuance_datetime");
CREATE INDEX patients_idx_id ON "patients" ("id");
CREATE INDEX reads_idx_read_datetime ON "reads" ("read_datetime");
The optimized query:
SELECT
        foo.pa_first_name,
        foo.pa_last_name,
        MAX(max_read) AS read_datetime,
        SUM(value) AS value,
        serial_number 
    FROM
        (SELECT
            pa_first_name,
            pa_last_name,
            value,
            serial_number,
            re_read_datetime,
            max_read 
        FROM
            ((SELECT
                pa.first_name AS pa_first_name,
                pa.last_name AS pa_last_name,
                value AS value,
                first_value(de.serial_number) OVER (PARTITION 
            BY
                pa.id 
            ORDER BY
                re.read_datetime DESC) AS serial_number,
                re.read_datetime AS re_read_datetime,
                MAX(re.read_datetime) OVER (PARTITION 
            BY
                pd.id ) AS max_read 
            FROM
                reads re 
            INNER JOIN
                devices de 
                    ON de.id = re.device_id 
            INNER JOIN
                patient_devices pd 
                    ON pd.device_id = de.id 
                    AND re.read_datetime >= pd.issuance_datetime 
                    AND (
                        (
                            pd.unassignment_datetime IS NULL 
                            AND 'infinity'::timestamp < re.read_datetime
                        )
                    ) 
            INNER JOIN
                patients pa 
                    ON pa.id = pd.patient_id 
            WHERE
                re.read_datetime BETWEEN '2012-01-01 10:30:01' AND '2013-05-18 03:03:42') 
        UNION
        DISTINCT (SELECT
            pa.first_name AS pa_first_name,
            pa.last_name AS pa_last_name,
            value AS value,
            first_value(de.serial_number) OVER (PARTITION 
        BY
            pa.id 
        ORDER BY
            re.read_datetime DESC) AS serial_number,
            re.read_datetime AS re_read_datetime,
            MAX(re.read_datetime) OVER (PARTITION 
        BY
            pd.id ) AS max_read 
        FROM
            reads re 
        INNER JOIN
            devices de 
                ON de.id = re.device_id 
        INNER JOIN
            patient_devices pd 
                ON pd.device_id = de.id 
                AND re.read_datetime >= pd.issuance_datetime 
                AND ((pd.unassignment_datetime < re.read_datetime)) 
        INNER JOIN
            patients pa 
                ON pa.id = pd.patient_id 
        WHERE
            re.read_datetime BETWEEN '2012-01-01 10:30:01' AND '2013-05-18 03:03:42')
    ) AS union1
) AS foo 
WHERE
read_datetime = max_read 
GROUP BY
foo.pa_first_name,
foo.pa_last_name,
serial_number 
ORDER BY
value DESC LIMIT 10

Related Articles



* original question posted on StackOverflow here.