Search code examples
postgresqlperformancesubquery

Does PostgreSQL deduplicate subqueries?


For example, do these differ in performance?

SELECT EXISTS (SELECT * FROM b WHERE a.col = b.col) AS e
FROM a
WHERE e
SELECT EXISTS (SELECT * FROM b WHERE a.col = b.col)
FROM a
WHERE EXISTS (SELECT * FROM b WHERE a.col = b.col)

Solution

  • The subquery will be evaluated twice. In your artificial case, you can avoid that by writing SELECT TRUE FROM a WHERE ..., but there is no general solution that works for every query.