SQL SERVER

What is CTE (Common Table Expression) in SQL Server?

CTE(Common Table Expression)
Written by shohal

CTE (Common Table Expression)

Common Table Expression, also called as CTE in short form, is a temporary named result set that you can reference within a SELECT, INSERT, UPDATE, or DELETE statement.

Where CTE (Common Table Expression) result set will be stored?

CTE results are not stored anywhere, they don’t produce results, a CTE is just a definition, just like a VIEW is just a definition. Think of a CTE as being a View that only lasts for the duration of the query.

Syntax for creating a CTE:

WITH cte_name (Column1, Column2, ..)
AS
( CTE_query )

SQL query using CTE:

With EmpCount(DepId, TotalEmp)
as
(
 Select DepId, COUNT(*) as TotalEmp
 from tblEmp
 group by DepId
)

Select DeptName, TotalEmp
from tblDep
join EmpCount
on tblDep.DeptId = EmpCount.DepId
order by TotalEmp

CTE can only be referenced by a SELECT, INSERT, UPDATE, or DELETE statement, that immediately follows the CTE. If you try to do something else in between, we get an error stating – ‘Common table expression defined but not used’.

IT is also, possible to create multiple CTE using a single WITH clause.

About the author

shohal

I have profession and personal attachment with custom ERP Software development, Business Analysis, Project Management and Implementation almost (36) ,also Oracle Apex is my all-time favorite platform to developed the software. Moreover i have some website development experience with WordPress. For hand on networking experience DevOps and CCNA, it create me a full package. Here are some core programming language with networking course i have been worked: Oracle SQL ,PL/SQL,Oracle 19c Database , Oracle Apex 20.1,WordPress,Asp.Net ,MS SQL ,CCNA ,Dev Ops, SAP SD

Leave a Comment