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:
ALTER TABLE `care_connect` ADD INDEX `care_connect_idx_clinic_id_role_status` (`clinic_id`,`role`,`status`);
ALTER TABLE `diary` ADD INDEX `diary_idx_state_meal_type_recorded` (`state`,`meal_type`,`recorded_at`);
ALTER TABLE `diary` ADD INDEX `diary_idx_state_recorded_at` (`state`,`recorded_at`);
SELECT
d_user_id,
d_recorded_at,
d_glucose_value,
d_unit
FROM
((SELECT
d.user_id AS d_user_id,
d.recorded_at AS d_recorded_at,
d.glucose_value AS d_glucose_value,
d.unit AS d_unit
FROM
diary AS d
JOIN
(
SELECT
u.id
FROM
health_user AS u
JOIN
(
SELECT
DISTINCT care_connect.user_id
FROM
care_connect
WHERE
care_connect.clinic_id = 217
AND care_connect.role = 'user'
AND care_connect.status = 'active'
) AS c
ON u.id = c.user_id
WHERE
u.is_tester IS FALSE
) AS cu
ON d.user_id = cu.id
WHERE
d.created_at >= d.recorded_at
AND d.recorded_at < current_date
AND d.recorded_at >= current_date - INTERVAL '30 days'
AND d.glucose_value > 0
AND (
(
d.state = 'before_meal'
AND d.meal_type = 'breakfast'
)
)
)
UNION
DISTINCT (SELECT
d.user_id AS d_user_id,
d.recorded_at AS d_recorded_at,
d.glucose_value AS d_glucose_value,
d.unit AS d_unit
FROM
diary AS d
JOIN
(SELECT
u.id
FROM
health_user AS u
JOIN
(SELECT
DISTINCT care_connect.user_id
FROM
care_connect
WHERE
care_connect.clinic_id = 217
AND care_connect.role = 'user'
AND care_connect.status = 'active') AS c
ON u.id = c.user_id
WHERE
u.is_tester IS FALSE) AS cu
ON d.user_id = cu.id
WHERE
d.created_at >= d.recorded_at
AND d.recorded_at < current_date
AND d.recorded_at >= current_date - INTERVAL '30 days'
AND d.glucose_value > 0
AND (d.state = 'wakeup'))
) AS union1