3

A SELECT query, which is an intermediate result for another query, as known, can be either written by a CTE, view or a nested SELECT query (SELECT * FROM (SELECT ... ) a).

Now I want to build a query use one of the three methods as the intermediate result. Should my query logic remains same, is there any difference on performance when using one of the three methods to build my query? (During my build, no advanced and specific topic on either way is used, such as recursive CTE, indexed view, USING ...MERGE ... etc., just fundamental syntax but complexity might be high.)

4
  • 2
    I believe CTEs will just be inlined and run, and then would behave the same as the query without a CTE. A materialized view could perform faster. Commented Oct 12, 2018 at 3:48
  • Views are something entirely different. CTE and sub queries are essentially the same except when the CTE is recursive. Commented Oct 12, 2018 at 5:27
  • Write whatever is most straightforward for you to read. Test it. Does it perform adequately compared to your performance goals? Great, move on. If not, try variants. But assuming your code is correctly written in each variant, overall performance is likely to be similar or identical (ignoring materialized/indexed views). Don't try to learn "rules" of the form "X is faster then Y". Even when such rules may exist, the sheer number of accompanying caveats and exceptions (and the sheer number of rules) makes them far less than generally applicable. Commented Oct 12, 2018 at 7:52
  • Possible duplicate of SQL - CTE vs VIEW Commented Aug 20, 2019 at 11:42

2 Answers 2

4

CTE is just syntax so in theory it is just a subquery. you may not get any performance difference while using CTE and Subquery.

I think the biggest benefit for using CTEs is readability. It makes it much easier to see what queries are being used as subqueries, and then it's easy to join them into a query, much like a view.

Now about CTE and View Hope you can read this and see what is suitable for you.

CTE vs View Performance in SQL Server

SQL - CTE vs VIEW

Its also depends how you designed you query and script structure.

0

The answer is NO.

CTE, View and Subquery depends on your Script Structure. Much better to learn Techniques for improving the performance of SQL queries.

Take a look at this link

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.