I have begun reading about Common Table Expression and cannot think of a use case where I would need to use them. They would seem to be redundant as the same can be done with derived tables. Is there something I am missing or not understanding well? Can someone give me a simple example of limitations with regular select, derived or temp table queries to make the case of CTE? Any simple examples would be highly appreciated.
相关问题
- SQL join to get the cartesian product of 2 columns
- sql execution latency when assign to a variable
- Difference between Types.INTEGER and Types.NULL in
- What is the best way to cache a table from a (SQL)
- php PDO::FETCH_ASSOC doesnt detect select after ba
There are two reasons I see to use cte's.
To use a calculated value in the where clause. This seems a little cleaner to me than a derived table.
Suppose there are two tables - Questions and Answers joined together by Questions.ID = Answers.Question_Id (and quiz id)
Here's another example where I want to get a list of questions and answers. I want the Answers to be grouped with the questions in the results.
It is very useful when you want to perform an "ordered update".
MS SQL does not allow you to use ORDER BY with UPDATE, but with help of CTE you can do it that way:
Look here for more info: How to update and order by using ms sql
One of the scenarios I found useful to use CTE is when you want to get DISTINCT rows of data based on one or more columns but return all columns in the table. With a standard query you might first have to dump the distinct values into a temp table and then try to join them back to the original table to retrieve the rest of the columns or you might write an extremely complex partition query that can return the results in one run but in most likelihood, it will be unreadable and cause performance issue.
But by using CTE (as answered by Tim Schmelter on Select the first instance of a record)
As you can see, this is much easier to read and maintain. And in comparison to other queries, is much better at performance.