4 ms·
In PostgreSQL, you can use CTEs to force certain subqueries to run before others. That technique would be useful here, and would clean up the code a bit.
by joevandyk 13y ago
In PostgreSQL, you can use CTEs to force certain subqueries to run before others. That technique would be useful here, and would clean up the code a bit.
- bgilroy26 13y agoI didn't know what Common Table Expressions were. I had always called them WITH queries. It's good to learn the name. http://www.postgresql.org/docs/8.4/static/queries-with.html http://www.postgresql.org/docs/8.4/static/queries-with.html
- brunnsbe 13y agoCTEs are found in SQL Server as well: http://technet.microsoft.com/en-us/library/ms190766(v=sql.105).aspx http://technet.microsoft.com/en-us/library/ms190766(v=sql.10...
- pradocchia 13y agobut CTEs in SQL Server are not an optimization boundary like they are in Postgres. This makes a big difference in their proper use. In SQL Server, aside from recursion, CTEs are purely syntactic sugar and thus a tool for organizing code. Whereas in Postgres, due to the optimization boundary, they are a tool for query tuning. If you rewrite a query in Postgres using CTEs just to clean it up, you are doing it wrong, since the CTEs will also affect the planner.
- radiowave 13y agoRight, but that's assuming that performance is the most pressing constraint. Sometimes it's confidence in the query producing the right result, or maintenance further down the line.
- atwebb 13y agoAm I incorrect in stating that this isn't necessarily true? Just because a statement is earlier in a script doesn't mean it will be optimized first.
- joevandyk 13y agoIn Postgres, common table expressions are planned and executed separately. I think of it as each section builds a temp table. This can be a good or bad thing, but it's sometimes important to know that it's happening.