[Solved] Slow PostgreSQL Query for Mins and Maxs within equal intervals in a time period

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 Selecting Unnecessary Columns (query line: 8): 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:
CREATE INDEX devices_idx_customer_id ON "devices" ("customer_id");
CREATE INDEX sample_data_idx_time ON "sample_data" ("time");
CREATE INDEX sample_data_idx_device_id_time ON "sample_data" ("device_id","time");
CREATE INDEX sample_data_idx_sample ON "sample_data" ("sample" desc);
The optimized query:
WITH periods AS (SELECT
        time.start AS st,
        time.start + (INTERVAL '1 year' / 100) AS en 
    FROM
        generate_series(now() - INTERVAL '1 year',
        now(),
        INTERVAL '1 year' / 100) AS time(start)) SELECT
        s.* 
    FROM
        sample_data s 
    JOIN
        periods 
            ON s.time BETWEEN periods.st AND periods.en 
    JOIN
        devices d 
            ON d.customer_id = 23 
    WHERE
        s.id = (
            SELECT
                sample_data.id 
            FROM
                sample_data 
            WHERE
                sample_data.device_id = d.id 
                AND sample_data.time BETWEEN periods.st AND periods.en 
            ORDER BY
                sample_data.sample ASC LIMIT 1
        ) 
        OR s.id = (
            SELECT
                sample_data.id 
            FROM
                sample_data 
            WHERE
                sample_data.device_id = d.id 
                AND sample_data.time BETWEEN periods.st AND periods.en 
            ORDER BY
                sample_data.sample DESC LIMIT 1
        )

Related Articles



* original question posted on StackOverflow here.