6 comments

  • vlaaad2 hours ago
    Use the term, never define the term, classic.<p>CTE stands for Common Table Expressions in SQL. They are temporary result sets defined within a single query using the WITH clause, acting like named subqueries to improve readability and structure.
    • radimm2 hours ago
      OP here, damn - that&#x27;s a very good point. Can&#x27;t believe I missed it.
      • iainmerrick1 hour ago
        From the headline, I thought it might be about sports-related concussions!<p>I was morbidly curious what a &quot;good CTE&quot; could possibly be...
  • uwemaurer34 minutes ago
    Great article, I always like to structure my queries with CTEs and I was (wrongly) assuming it all gets inlined at the end. Sometimes it also gets complicated since these intermediate results can&#x27;t be easily seen in a SQL editor. I was working on a UI to parse CTE queries and then execute them step by step to show the results of all the CTEs for easier understanding of the query (as part of this project <a href="https:&#x2F;&#x2F;github.com&#x2F;sqg-dev&#x2F;sqg&#x2F;" rel="nofollow">https:&#x2F;&#x2F;github.com&#x2F;sqg-dev&#x2F;sqg&#x2F;</a>)
  • dspillett1 hour ago
    I wrangle databases by day, and do martial arts of an evening. Two arenas where CTEs can cause significant headaches!
  • yen2231 hour ago
    I&#x27;ve always thought of CTEs as a code organisation tool, not an optimisation tool. The fact the some rdbms treats them as an optimisation fence was a bug, not a feature.
    • solumunus1 hour ago
      Improved readability is definitely the primary benefit.
  • qwertydog1 hour ago
    Great post - thanks. I think the columns in the index you suggested in the pre-pg12 section are in the wrong order (that index would get used)
    • radimm1 hour ago
      Thanks - I will recheck later today.
  • bob10291 hour ago
    &gt; Recursive CTEs use an iterative working-table mechanism. Despite the name, they aren&#x27;t truly recursive. PostgreSQL doesn&#x27;t &quot;call itself&quot; by creating a nested stack of unfinished queries.<p>If you want something that is more like actual recursion (I.e., depth-first), Oracle has CONNECT BY which does not require the same kind of tracking. It also comes with extra features to help with cycle detection, stack depth reflection, etc.<p>If your problem is aligned with the DFS model, the oracle technique can run circles around recursive CTEs. Anything with a deep hierarchy and early termination conditions is a compelling candidate.