What are the trade-offs between using a Subquery and a Common Table Expression (CTE)? When would you prefer a Recursive CTE?
Last updated
Subqueries and CTEs (
WITH) usually perform the same. Subqueries are compact for one-off logic but get unreadable when nested and can't be referenced twice.CTEs read top-to-bottom and can be referenced multiple times. In some engines they act as an optimization fence (materialized), which can hurt performance.
Use a recursive CTE for self-referencing data (hierarchies, graph traversal, number/date sequences). It unions an anchor member with a recursive member until no new rows appear.
- https://techedge.in/posts/cte-vs-subquery-vs-temp-table.html
- https://medium.com/@shivarajsgalagali5/cte-vs-subqueries-vs-rank-when-to-use-which-and-why-ad1b805b4142
- https://dev.to/loi2008/unlocking-the-power-of-sql-subqueries-ctes-and-stored-procedures-demystified-4aci
- https://medium.com/@dilanhosgoren1/subquery-vs-cte-with-in-postgresql-when-should-you-use-which-c21634faeeab
- https://www.postgresql.org/docs/current/queries-with.html
- https://easyspawn.com/blog/postgres-cte
- https://postgres.fm/episodes/data-model-trade-offs
- https://learnsql.com/blog/cte-vs-subquery/