• 13. 1. 2020
  • Ing. Jan Zedníček - Data & Finance
  • 0

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
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 (
    ROUND(SUM(Amount),2) AS SUM_Amount,
    RANK() OVER (ORDER BY SUM(Amount) desc) AS Order
  FROM AdventureWorksDW2014.dbo.FactFinance
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

  ROUND(SUM(Amount),2) AS SUM_Amount,
  RANK() OVER (ORDER BY SUM(Amount) desc) as Order
FROM AdventureWorksDW2014.dbo.FactFinance
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


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

Rate this post

Ing. Jan Zedníček - Data & Finance

My name is Jan Zedníček and I work as a freelancer. I have been working as a freelancer for many companies for more than 10 years.
I used to work as a financial controller, analyst and manager at many different companies in field of banking and manufacturing. When I am not at work, I like playing volleyball, chess, doing a workout in the gym.

Leave a Reply

Your email address will not be published. Required fields are marked *