Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the advantage of common table expression in sql server

we write CTE sql like below one

WITH yourCTE AS 
(
 SELECT .... FROM :... WHERE.....
) SELECT * FROM yourCTE

what would be advantage to put sql in with block. i think that if we put complicated sql in with block then we just can write sql like SELECT * FROM yourCTE. as if i am accessing view. what is added advantage of using CTE in terms of performance. please discuss. thanks

like image 498
Thomas Avatar asked Mar 03 '11 06:03

Thomas


People also ask

What is advantage of CTE in SQL Server?

1. Using CTE improves the readability and makes maintenance of complex queries easy. 2. The query can be divided into separate, simple, logical building blocks which can be then used to build more complex CTEs until final result set is generated.

Why would you use common table expression in SQL?

CTEs, like database views and derived tables, enable users to more easily write and maintain complex queries via increased readability and simplification. This reduction in complexity is achieved by deconstructing ordinarily complex queries into simple blocks to be used, and reused if necessary, in rewriting the query.

What is the advantage of a CTE common table expression in place of a sub query?

Advantage of Using CTE CTE can be more readable: Another advantage of CTE is CTE are more readable than Subqueries. Since CTE can be reusable, you can write less code using CTE than using subquery. Also, people tend to follow the logic and ideas easier in sequence than in a nested fashion.


1 Answers

  1. Making recursive query.
  2. Hold a query output virtually in a temporary area named as given while definition.
  3. No need to save Meta data.
  4. Useful when there is need to do more operation on some query output.
  5. Query output retain while till then query is running
  6. Best use of holding temporary data for further processing.
  7. Allow more grouping option than a single query.
  8. Allow to get scalar data from a complicated query
like image 119
Raj Kumar Avatar answered Oct 10 '22 19:10

Raj Kumar