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:
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);
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
)