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 person_idx_user_id_gender_age ON "person" ("user_id","gender","age");
CREATE INDEX person_idx_user_id_gender_household ON "person" ("user_id","gender","household_id");
CREATE INDEX person_idx_household_id_age ON "person" ("household_id","age");
SELECT
a.household_id household_id,
age_of_youngest_woman,
b.number_of_children,
c.number_of_men,
fertility_cond_prob_number_of_children.cond_prob cond_prob_number_of_children,
fertility_cond_age.cond_prob cond_prob_age,
fertility_cond_prob_number_of_children.cond_prob * fertility_cond_age.cond_prob total_cond_prob,
random() <= (874. / 1703.) is_newborn_male
FROM
(SELECT
person.household_id,
MIN(person.age) age_of_youngest_woman
FROM
person
WHERE
(
person.user_id = 1
)
AND (
person.gender = 'FEMALE'
)
AND (
person.age >= 18
)
GROUP BY
person.household_id) a
LEFT JOIN
(
SELECT
person.household_id,
COUNT(*) number_of_children
FROM
person
WHERE
(
person.user_id = 1
)
AND (
person.gender = 'CHILD'
)
GROUP BY
person.household_id
) b
ON (
a.household_id = b.household_id
)
INNER JOIN
(
SELECT
person.household_id,
COUNT(*) number_of_men
FROM
person
WHERE
(
person.user_id = 1
)
AND (
person.gender = 'MALE'
)
AND (
person.age >= 18
)
GROUP BY
person.household_id
HAVING
(
number_of_men > 0
)
) c
ON (
a.household_id = c.household_id
)
LEFT JOIN
fertility_cond_prob_number_of_children
ON (
fertility_cond_prob_number_of_children.number_of_children = b.number_of_children
)
LEFT JOIN
fertility_cond_age
ON (
fertility_cond_age.age = age_of_youngest_woman
)
WHERE
(
1 = 1
)
AND (
random() <= (
fertility_cond_prob_number_of_children.cond_prob * fertility_cond_age.cond_prob
)
)