Back to Blog

SQL With - How to Use the WITH Statement/Common Table Expressions (CTE) in SQL Server - SQL Training Online

Write readable queries with Common Table Expressions (CTE). Learn WITH statement syntax, recursive CTEs, and query optimization in SQL Server.

3 min read

Last updated on

In this video, I introduce the SQL WITH statement (also known as Common Table Expressions or CTE) and show you the basics of how it is used.

[/sharebox5_no_text]

The SQL WITH Statement is called Common Table Expressions or CTE for short in SQL Server

The SQL WITH statement is used for 2 primary reasons:

  1. To move Subqueries to make the SQL easier to read.

  2. To do recursive queries in SQL

Today, I just want to talk about the subquery piece.

I first want to take a look at the Employee table in the SQL Training Online Simple Database.

select * from employee

To talk about the SQL WITH statement, I have to first talk about and show you a subquery. SQL With Statement

select *

from

(

select * from employee

) a

So that is an example of a subquery.

But, we want to talk about the SQL WITH, which allows you to move the subquery up and make the SQL a lot easier to read.

Here is the same query using the WITH statement.

WITH cteEmployee (employee_number,employee_name,manager)

AS

(

select employee_number,employee_name,manager from employee

)

select *

from cteEmployee

You can see that we start with the WITH clause and then we can use any name we want to name our CTE. In this case, I use -cteEmployee-.

Then we need to specify the columns inside of parenthesis.

Next comes the AS clause.

And finally, we just SELECT from the cteEmployee table we created.

And, that-s it.

But, I want to take it a step further and join the cteEmployee CTE back to the Employee table and get the Manager-s name.

Here is an example of that.

WITH cteEmployee (employee_number,employee_name,manager)

AS

(

select employee_number,employee_name,manager from employee

)

select cte.employee_number

,cte.employee_name

,cte.manager

,e.employee_name as manager_name

from cteEmployee cte INNER JOIN employee e on cte.manager = e.employee_number

That-s it.

That is the basic introduction into the SQL WITH statement in SQL Server. Microsoft also has some good examples on this.

Let me know what you think by commenting or sharing on twitter, facebook, google+, etc.

About Joey Blue

Joey Blue teaches practical data skills that companies actually use. With 25+ years of experience solving real data problems for Fortune 500 companies, he's helped 152,000+ students learn SQL, Power BI, reporting, and modern analytics—cutting straight to what works.