SQL CTE (Common Table Expressions) With Examples – More Organized Queries and Procedures

Last modified date:

SQL CTE or so called Common table expression is simply put a temporary table (or better said it is a result set) in form of an expression. We can refer to it in SELECT, INSERT, DELETE or UPDATE script after its declaration using clause WITH.

We can make recursive queries using CTE (it is even recommended) in case when we have parent – child hierarchy defined in a table.  For example in form of self reference foreign key.

SQL CTE Syntax

WITH Alias_Query AS (
SELECT Column1, Column2
FROM dbo.Table
)
SELECT *
FROM Alias_Query;

We define alias using WITH clause as a result of a query and we can refer to this alias afterwards.

Complex nested queries or inserting script results into multiple temp tables is not necessary with complex queries. Resulting scripts are therefore more elegant, readable and shorter.

CTE must be used with some sense. If we work with big amount of data and commence very complex operations, CTE will be slower than temp tables. CTE is not materialized as opposed to inserting into #temp.

Example of SQL CTE with WITH clause – non-recursive query

Let’s have a situation where we have table with sales and we want to display TOP 10 days regarding sales. Firstly there is a need to do daily ranking and the choose top 10 days.

WITH Revenue_Order_ByDays AS (
  SELECT
    DATEKey,
    ROUND(SUM(Amount),2) AS SUM_Amount,
    RANK() OVER (ORDER BY SUM(Amount) desc) AS Order
  FROM AdventureWorksDW2014.dbo.FactFinance
  GROUP BY DATEKey
)
SELECT *
FROM Revenue_Order_ByDays
WHERE Order <= 10;

Firstly we alias query using t-sql CTE WITH which will rank all sales day by day in descending order. Following query then selects TOP 10 days together with sales.

UPDATE, INSERT, DELETE can be approached in same way as shows the example. Only swap SELECT and use correct syntax.

BTW if you would like to query TOP  10 as shown below, the result will be error. Therefore I chose this example as it is quite common usage. You will certainly find much more of them.

Querying for window functions in this manner is a mistake. That is why we used t-sql CTE with WITH

SELECT
  DATEKey,
  ROUND(SUM(Amount),2) AS SUM_Amount,
  RANK() OVER (ORDER BY SUM(Amount) desc) as Order
FROM AdventureWorksDW2014.dbo.FactFinance
GROUP BY DATEKey
HAVING RANK() OVER (ORDER BY SUM(Amount) desc) <= 10;

The script above will result in an error: Windowed functions can only appear in the SELECT or ORDER BY clauses

SQL CTE s WITH

Recursive queries will be mentioned some other time. Hierarchies are huge topic and will definitely take up a whole article.

My name is Jan Zedníček and I work as a BI Developer at Kentico Software in Brno. Mostly you can see me there working in the office, but I also work partly as a freelancer. I have been working as a freelancer for many companies for more than 5 years, but Kentico is the matter of my heart. I used to work as a financial controller at companies like Aero Vodochody or Sberbank and I also used to be a bond program manager in Unicapital Investment group. When I am not at work, I like playing volleyball, chess, doing a workout in the gym and I enjoy tasting of best quality rums. I am trying to summarize all my knowledge on this website not to forget them (because of the rum effect, you know =) and to put them forward to anyone. Don´t worry about asking for help or writing some comments.

Category: SQL Commands Tags:

About Ing. Jan Zedníček - BI Developer, Finance controller

My name is Jan Zedníček and I work as a BI Developer at Kentico Software in Brno. Mostly you can see me there working in the office, but I also work partly as a freelancer. I have been working as a freelancer for many companies for more than 5 years, but Kentico is the matter of my heart. I used to work as a financial controller at companies like Aero Vodochody or Sberbank and I also used to be a bond program manager in Unicapital Investment group. When I am not at work, I like playing volleyball, chess, doing a workout in the gym and I enjoy tasting of best quality rums. I am trying to summarize all my knowledge on this website not to forget them (because of the rum effect, you know =) and to put them forward to anyone. Don´t worry about asking for help or writing some comments.

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.