SQL CTEs Performance

The cluster focuses on Common Table Expressions (CTEs) in SQL, especially their performance impacts in PostgreSQL such as acting as optimization barriers in older versions, improvements in recent releases, and comparisons to subqueries or recursive CTEs.

📉 Falling 0.3x Databases
1,586
Comments
19
Years Active
5
Top Authors
#3246
Topic ID

Activity Over Time

2007
3
2009
15
2010
4
2011
8
2012
31
2013
28
2014
84
2015
115
2016
86
2017
51
2018
85
2019
122
2020
153
2021
142
2022
147
2023
239
2024
154
2025
117
2026
2

Keywords

e.g InterSystems WITH HAVING JS DB2 POS CTE SQL SUM recursive sql postgres queries query clauses table select activerecord postgresql

Sample Comments

cjv Jul 30, 2020 View on HN

Can you give a situation where CTEs are still a optimization barrier in Postgres?

cerved Jan 13, 2023 View on HN

I don't think recursive CTEs are that bad

nerdponx Nov 3, 2017 View on HN

I never understood this. Why can't CTEs be transparently compiled into subqueries?

haki Sep 21, 2020 View on HN

Starting at PostgreSQL 12 you don't even have to feel bad about all of those CTE's.

mason55 Jun 1, 2014 View on HN

I can't speak for any other server but Postgres recurvise CTEs should be reasonably performant

jansommer Dec 26, 2021 View on HN

CTE's are indeed nice, but can also make your queries substantially slower, at least in Postgres

dspillett Jun 25, 2021 View on HN

Careful with CTEs in older postgres. Until the most recent versions they were an optimisation fence (predicate push-down would not pass through, meaning the CTE would often result in an index or table scan, potentially multiple times in the recursive case. This can be a huge problem over large data, though obviously in many circumstances with small enough data it is still efficient enough.

epgui Jan 12, 2023 View on HN

Nope, there’s no performance downside to using CTEs in recent postgres versions, unless the CTE is recursive or has side effects (which would be weird).

jcheng May 22, 2025 View on HN

Or better yet, use CTEs: https://duckdb.org/docs/stable/sql/query_syntax/with.html

pg_bot Sep 4, 2019 View on HN

My ORM (and probably yours) handles CTEs ;)