Common Table Expression (CTE) in SQL Server

Common Table Expression (CTE) in SQL Server

What is CTE?

CTE stands for Common Table Expression. It allows us to define a temporary result set that we can query. It is not stored as an object in the memory and it only lasts for the duration of the query.

How do we create a CTE?

The basic syntax of CTE is as follows:

WITH cte_name (column_name1, column_name2...)
AS
( Write SQL statement here)

SELECT col_name
FROM cte_name;


WITH cte_name
AS
( Write SQL statement here)

SELECT col_name
FROM cte_name;

As shown in snippet 1 and 2, we start with a 'WITH' keyword followed by the name we want to give to our CTE. After that, we specify the aliases for the columns (as shown in snippet 1 as column_name1, column_name2...) but that is optional(See snippet 2. It is similar to snippet 1 except it does not have aliases) Next, we specify 'AS' and then define our SQL statement within the brackets. IMMEDIATELY after we define the CTE, we refer to the CTE and by referring we mean that we query the CTE as if we were to query any other table.

Let us see CTE in action with the help of an example. As shown below, we have a table called 'information' in which we have data about employees, their name, department and salary.

No alt text provided for this image

Now, let us create a CTE to find out the department(s) with 3 or more employees. First, we create a CTE that gives details about all the departments and the total number of employees in each department. Second, we query that CTE to fetch only those departments which have 3 or more employees.

No alt text provided for this image

We can see in the above-mentioned image that there are 4 departments with 3 or more employees.

Also, we need to keep in mind that since CTE temporarily holds the data, we need to query it IMMEDIATELY after we define it. If we specify any other query between our CTE and the SQL statement that queries that CTE, then we will get an error as shown in the picture below.

No alt text provided for this image

How is CTE useful?

1) It makes code simpler, reduces the complexity and hence, improves readability.

2) It can be used as a substitute for a view. (In case we do not have permission to create a view or we just want the query to run for one time and do not require to store it as a view)

3) It comes to the rescue when we want to perform an aggregate function on an aggregate function (multi-level aggregations). Let us see an example of this. We want to find out the average maximum salary. So, we will try to use AVG and MAX function on the salary column.

No alt text provided for this image

As we can see in the picture above, we get an error stating that we cannot perform an aggregate function on an aggregate. In such cases, using CTE would resolve the issue. Let us see how it can be done.

No alt text provided for this image

As we can see in the picture above, we can first create a CTE which temporarily holds the data of each department and its maximum salary and then we can query that to get the average of maximum salaries.


Surodeep Dey

AWS Data Engineer - Infosys|| Ex- ITC Infotech|| Ex- TCS || PGD in Data Science and AI|| Python|| PySpark|| AWS||SQL || PL/SQL ||Oracle 11g|| SVN || SQL server|| Service Now

3y

Thanks #Harsh_mehta for this awesome post. It help a lot today for writing a code. Thanks again

Like
Reply
Tusar J

Data Engineering & Database Development | Data Warehouse Developer | SQL Developer | Analytics Engineer

4y

Thank You! I'd be glad to see if you make an in-depth article on this as well!

Like
Reply
Rushabh Sanghvi

Experienced Software Technical Analyst | Networking Specialist | Microsoft Student Partner | Driving Innovation and Operational Excellence

4y

Great insight with examples!

Viraj Shah

Data Engineer and Team Leader @ EAB | MS in Information Systems

4y

Great stuff, very useful!

Like
Reply

A great introduction about CTE! Think CTE as a one-time View is a great comparison!

To view or add a comment, sign in

More articles by Harsh Mehta

  • Reset MySQL root password for Windows Systems

    If you want to reset the password for MySQL 'root'@'localhost' account then you can do it by following these steps…

    1 Comment
  • SQL Server Temporary Tables

    Temporary tables are the tables that exist temporarily on SQL Server. When we need to store the data temporarily, we…

    1 Comment
  • Different ways to handle NULLs in SQL Server

    Many times when we query the database, we get NULLs in the result set and we want to replace those NULLs with some…

    12 Comments
  • COUNT(*) vs COUNT(1) vs COUNT(column_name) in SQL Server

    COUNT function accepts only one argument and counts the number of rows. Let us understand this with an example.

    20 Comments

Insights from the community

Others also viewed

Explore topics