I have the following SQL Statement:
SELECT p.name
FROM person p
WHERE EXISTS (
SELECT 1
FROM task t
WHERE t.person_id = p.id
)
LIMIT 100
The task
table contains millions of entries. But somehow Postgres thinks it is smart to execute the inner select first. This results in the query to run for several minutes.
If I change the SELECT 1
to SELECT COUNT(1)
, I can trick Postgres into estimating that the inner select is more expensive. This results in the query being completed in less than a second.
How can I optimize the execution plan of Postgres without changing the above query?
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…