What is Common Table Expression (CTE)?

Thank you for reading this post, don't forget to subscribe!

A common table expression (CTE) is a temporary storage result set, which will be accessible within the next execution scope of a query. That means we didn’t get CTE result after the second query statement.  A CTE is similar to a derived table in that it is not stored as an object and lasts only for the duration of the query. Unlike a derived table, a CTE can be self-referencing and can be referenced multiple times in the same query.

A very simple example of Common Table Expression (CTE) in SQL Server for pagination

Suppose we have a table ‘Employee’ with following structure. Suppose we need to apply pagination for this table, that means fetch only some part of data within the given index.  To achieve this, we usually insert all records into a temporary table to get a new id column as row number. Then we have to fetch data from this table as per this new column.

Table Structure:

By using Common Table Expression (CTE) we can accomplish pagination query with single statement as follows. In our CTE we are fetching data with row number, and from this CTE we are fetching some range of data as we needed. This query helps to get pagination data in SQL Server using CTE with single execution of query. The scope of the CTE will be ended just after this execution of statement.

WITH CTE AS
(
SELECT id
,name
,age
,joindate
,ROW_NUMBER() OVER (ORDER BY id DESC) AS RowNumber
FROM employee
)
SELECT *
FROM CTE
WHERE RowNumber BETWEEN 1 AND 5;

OUTPUT: