The Wayback Machine - https://web.archive.org/web/20241001062601/https://www.geeksforgeeks.org/cte-in-sql/
Open In App

CTE in SQL

Last Updated : 06 Jun, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

The Common Table Expressions (CTE) were introduced into standard SQL in order to simplify various classes of SQL Queries for which a derived table was just unsuitable. CTE was introduced in SQL Server 2005, the common table expression (CTE) is a temporary named result set that you can reference within a SELECT, INSERT, UPDATE, or DELETE statement. You can also use a CTE in a CREATE view, as part of the view’s SELECT query. In addition, as of SQL Server 2008, you can add a CTE to the new MERGE statement. 

Why do We Need CTE in the SQL server?

A common table [deprecated]CTE is a powerful SQL construct that helps simplify queries. CTEs act as virtual tables (with records and columns) that are created during query execution, used by the query, and deleted after the query executes.

Using the CTE 

We can define CTEs by adding a WITH clause directly before the SELECT, INSERT, UPDATE, DELETE, or MERGE statement. The WITH clause can include one or more CTEs separated by commas. 

Syntax:

[WITH  [, …]]  

::=

cte_name [(column_name [, …])]

AS (cte_query) 

Argument

  1. Expression name: A valid identifier for a common table expression. The expression_name must be different from the names of other common table expressions defined in the same WITH  clause, but the expression_name can be the same as the name of the base table or view. All references to expression_name in the query use the common table expression instead of the base object.
  2. Column name: Specifies a column name in a common table expression. Duplicate names within a single CTE definition are not allowed. The number of column names must match the number of columns in the CTE_query_definition’s result set. A list of column names is optional only if all the resulting columns in the query definition have different names.
  3. CTE_QueryDefinition: Specifies a SELECT statement whose result set satisfies a common table expression. The SELECT statement for CTE_query_defining must meet the same requirements as creating a view, except that a CTE cannot define another CTE. For more information, see the Remarks section and CREATE VIEW (Transact-SQL). If multiple CTE_query_settings are defined, the query definitions must be combined with one of the set operators UNION ALL, UNION, EXCEPT, or INTERSECT.
     

Rules for Define and Use of Recursive Common Table Expressions
 

The following guidelines apply to defining recursive common table expressions:

  1. A recursive CTE definition must contain at least two he CTE query definitions, an anchor member and a recursive member. You can define multiple anchor and recursive members. However, all anchor member query definitions must be placed before the first recursive member definition. All CTE query definitions are anchor members unless they reference the CTE itself.
  2. Anchor elements must be combined with one of the following set operators: UNION ALL, UNION, INTERSECT, EXCEPT. UNION ALL is the only valid set operator between the last anchor member and the first recursive member when joining multiple recursive members. Anchor and recursive elements must have the same number of columns.
  3. The data type of the recursive member’s columns must be the same as the data type of the corresponding column of the anchor member.
  4. The following items are not allowed in her CTE_query_definition for recursive members:      
Please choose a different
grouping
PIVOT (For database compatibility level 110 and above.
See Breaking Changes to Database Engine Features in SQL Server 2016.
Offal Scalar aggregation Up
LEFT, RIGHT, OUTER JOIN (INNER JOIN is allowed)
subquery
A hint applied to recursive references to CTEs within a CTE_query_definition.

Creating a Recursive Common Table Expression 

A recursive CTE is one that references itself within that CTE. The recursive CTE is useful when working with hierarchical data as the CTE continues to execute until the query returns the entire hierarchy. 

A typical example of hierarchical data is a table that includes a list of employees. For every employee, the table provides a reference to that person’s manager. That reference is itself an employee ID within the same table. You can use a recursive CTE to display the hierarchy of employee data. 

If a CTE is created incorrectly it can enter an infinite loop. To prevent this, the MAXRECURSION hint can be added in the OPTION clause of the primary SELECT, INSERT, UPDATE, DELETE, or MERGE statement. 

A table is created: 

CREATE TABLE Employees
(
EmployeeID int NOT NULL PRIMARY KEY,
FirstName varchar(50) NOT NULL,
LastName varchar(50) NOT NULL,
ManagerID int NULL
)

INSERT INTO Employees VALUES (1, 'Ken', 'Thompson', NULL)
INSERT INTO Employees VALUES (2, 'Terri', 'Ryan', 1)
INSERT INTO Employees VALUES (3, 'Robert', 'Durello', 1)
INSERT INTO Employees VALUES (4, 'Rob', 'Bailey', 2)
INSERT INTO Employees VALUES (5, 'Kent', 'Erickson', 2)
INSERT INTO Employees VALUES (6, 'Bill', 'Goldberg', 3)
INSERT INTO Employees VALUES (7, 'Ryan', 'Miller', 3)
INSERT INTO Employees VALUES (8, 'Dane', 'Mark', 5)
INSERT INTO Employees VALUES (9, 'Charles', 'Matthew', 6)
INSERT INTO Employees VALUES (10, 'Michael', 'Jhonson', 6)

After the Employees table is created, the following SELECT statement, which is preceded by a WITH clause that includes a CTE named cteReports is created: 

WITH
cteReports (EmpID, FirstName, LastName, MgrID, EmpLevel)
AS
(
SELECT EmployeeID, FirstName, LastName, ManagerID, 1
FROM Employees
WHERE ManagerID IS NULL
UNION ALL
SELECT e.EmployeeID, e.FirstName, e.LastName, e.ManagerID,
r.EmpLevel + 1
FROM Employees e
INNER JOIN cteReports r
ON e.ManagerID = r.EmpID
)
SELECT
FirstName + ' ' + LastName AS FullName,
EmpLevel,
(SELECT FirstName + ' ' + LastName FROM Employees
WHERE EmployeeID = cteReports.MgrID) AS Manager
FROM cteReports
ORDER BY EmpLevel, MgrID

Thus, CTEs can be useful when you need to generate temporary result sets that can be accessed in a SELECT, INSERT, UPDATE, DELETE, or MERGE statement.

Features and Limitations of Common Table Expressions in Azure

The current implementation of CTEs in Azure Synapse Analytics and Analytics Platform System (PDW) has the following features and limitations:

  1. A CTE can be only specified in a SELECT statement.
  2.  A CTE can be only specified in a CREATE VIEW statement.
  3. A CTE can be only specified in a CREATE TABLE AS SELECT (CTAS) statement.
  4. A CTE can be only specified in a CREATE REMOTE TABLE AS SELECT (CRTAS) statement.
  5. A CTE can be only specified in a CREATE EXTERNAL TABLE AS SELECT (CETAS) statement.

Previous Article
Next Article

Similar Reads

Recursive CTE in SQL Server
CTE which is the abbreviation for Common Table Expression is an SQL Server tool that returns a temporary data set that can be used by another query. In this article, we are going to learn about the Implementation of Recursive CTE in SQL servers. We will understand how recursive common table expressions work step by step and understand their workflo
7 min read
MySQL | Recursive CTE (Common Table Expressions)
What is a CTE? In MySQL every query generates a temporary result or relation. In order to give a name to those temporary result set, CTE is used. A CTE is defined using WITH clause. Using WITH clause we can define more than one CTEs in a single statement. A CTE can be referenced in the other CTEs that are part of same WITH clause but those CTEs sho
5 min read
How to Print the Starting and End Position of Each Word Using CTE?
The Common Table Expressions (CTE) were introduced into standard SQL in order to simplify various classes of SQL Queries for which a derived table was just unsuitable. In this article, we will see, that in a given string, which contains alphabets and asterisks, print the starting and end position of each word. Steps To Print the Starting and End Po
2 min read
How to Implement Recursive CTE for Hierarchical Query to MariaDB?
Hierarchical data structures such as organizational hierarchies, file systems or product sections are common to find in the database. MariaDB an open-source relational database management system, offers several methods for querying hierarchical information, among them Recursive Common Table Expressions (CTEs) as a highly efficient and versatile opt
3 min read
Difference between Structured Query Language (SQL) and Transact-SQL (T-SQL)
Structured Query Language (SQL): Structured Query Language (SQL) has a specific design motive for defining, accessing and changement of data. It is considered as non-procedural, In that case the important elements and its results are first specified without taking care of the how they are computed. It is implemented over the database which is drive
2 min read
Configure SQL Jobs in SQL Server using T-SQL
In this article, we will learn how to configure SQL jobs in SQL Server using T-SQL. Also, we will discuss the parameters of SQL jobs in SQL Server using T-SQL in detail. Let's discuss it one by one. Introduction :SQL Server Agent is a component used for database task automation. For Example, If we need to perform index maintenance on Production ser
7 min read
SQL vs NO SQL vs NEW SQL
SQL stands for Structured Query Language. Which is based on relational algebra and schema is fixed in this which means data is stored in the form of columns and tables. SQL follows ACID properties which means Atomicity, Consistency, Isolation, and Durability are maintained. There are three types of languages present in SQL : Data Definition Languag
2 min read
SQL | Difference between functions and stored procedures in PL/SQL
Prerequisite: Procedures in PL/SQLFunctions in PL/SQL.Difference between functions and stored procedures in PL/SQL Differences between Stored procedures(SP) and Functions(User-defined functions (UDF)): 1. SP may or may not return a value but UDF must return a value. The return statement of the function returns control to the calling program and ret
3 min read
SQL SERVER – Input and Output Parameter For Dynamic SQL
An Input Parameter can influence the subset of rows it returns from a select statement within it. A calling script can get the value of an output parameter. An aggregate function or any computational expression within the stored process can be used to determine the value of the output parameter. A parameter whose value is given into a stored proced
3 min read
Difference between T-SQL and PL-SQL
1. Transact SQL (T-SQL) : T-SQL is an abbreviation for Transact Structure Query Language. It is a product by Microsoft and is an extension of SQL Language which is used to interact with relational databases. It is considered to perform best with Microsoft SQL servers. T-SQL statements are used to perform the transactions to the databases. T-SQL has
3 min read
SQL Server | Convert tables in T-SQL into XML
In this, we will focus on how tables will be converted in T-SQL into XML in SQL server. And you will be able to understand how you can convert it with the help of command. Let's discuss it one by one. Overview :XML (Extensible Markup Language) is a markup language similar to HTML which was designed to share information between different platforms.
2 min read
SQL - SELECT from Multiple Tables with MS SQL Server
In SQL we can retrieve data from multiple tables also by using SELECT with multiple tables which actually results in CROSS JOIN of all the tables. The resulting table occurring from CROSS JOIN of two contains all the row combinations of the 2nd table which is a Cartesian product of tables. If we consider table1 contains m rows and table2 contains n
3 min read
How to Execute SQL Server Stored Procedure in SQL Developer?
A stored procedure is a set of (T-SQL ) statements needed in times when we are having the repetitive usage of the same query. When there is a need to use a large query multiple times we can create a stored procedure once and execute the same wherever needed instead of writing the whole query again. In this article let us see how to execute SQL Serv
2 min read
SQL Query to Check if Date is Greater Than Today in SQL
In this article, we will see the SQL query to check if DATE is greater than today's date by comparing date with today's date using the GETDATE() function. This function in SQL Server is used to return the present date and time of the database system in a ‘YYYY-MM-DD hh:mm: ss. mmm’ pattern. Features: This function is used to find the present date a
2 min read
SQL Query to Add a New Column After an Existing Column in SQL
Structured Query Language or SQL is a standard Database language that is used to create, maintain and retrieve data from relational databases like MySQL, Oracle, SQL Server, Postgres, etc. In Microsoft SQL Server, we can change the order of the columns and can add a new column by using ALTER command. ALTER TABLE is used to add, delete/drop or modif
3 min read
SQL Query to Convert Rows to Columns in SQL Server
In this article we will see, how to convert Rows to Column in SQL Server. In a table where many columns have the have same data for many entries in the table, it is advisable to convert the rows to column. This will help to reduce the table and make the table more readable. For example, Suppose we have a table given below: NAMECOLLEGEROLL NUMBERSUB
2 min read
Dynamic SQL in SQL Server
In SQL Server, at times the SQL Queries need to be dynamic and not static, meaning the complete SQL query may be built dynamically at run time as a string using the user inputs and any specific application logic. This can be done in queries run from back-end applications or inside stored procedures. In this article let us look into the details abou
6 min read
Dynamic SQL and Temporary Tables in SQL Server
In SQL Server, creating and using Temp Tables using dynamic SQL is a good feature when we need to temporarily create tables at run time and delete automatically all within a session. They can be very useful when we need to store temporary data in a structured format and do data manipulation using Data Manipulation Language in SQL. In this article l
6 min read
How to SQL Select from Stored Procedure using SQL Server?
There may be situations in SQL Server where you need to use a stored procedure to get data from a SQL query. For direct data selection from a stored procedure within a query, SQL Server offers options like OPENQUERY and OPENROWSET. The usual way is running the stored procedure independently and then querying the outcomes. The idea of utilizing SQL
3 min read
SQL Quiz : Practice SQL Questions Online
This SQL quiz covers various topics like SQL basics, CRUD operations, operators, aggregation functions, constraints, joins, indexes, transactions, and query-based scenarios. We've included multiple-choice questions, fill-in-the-blank questions, and interactive coding challenges to keep things interesting and challenging. Whether you're a beginner l
3 min read
BULK INSERT in SQL Server(T-SQL command)
BULK INSERT in SQL Server(T-SQL command): In this article, we will cover bulk insert data from csv file using the T-SQL command in the SQL server and the way it is more useful and more convenient to perform such kind of operations. Let's discuss it one by one.  ConditionSometimes there is a scenario when we have to perform bulk insert data from .cs
3 min read
SQL Exercises : SQL Practice with Solution for Beginners and Experienced
SQL (Structured Query Language) is a powerful tool used for managing and manipulating relational databases. Whether we are beginners or experienced professionals, practicing SQL exercises is important for improving your skills. Regular practice helps you get better at using SQL and boosts your confidence in handling different database tasks. So, in
15+ min read
Difference between SQL and T-SQL
SQL (Structured Query Language) is the standard language for managing and manipulating relational databases, enabling operations like querying, updating, and deleting data. T-SQL (Transact-SQL), an extension of SQL developed by Microsoft, adds advanced features and procedural capabilities specifically for SQL Server. In this article, We will learn
4 min read
NULL values in SQL
In SQL there may be some records in a table that do not have values or data for every field and those fields are termed as a NULL value. NULL values could be possible because at the time of data entry information is not available. So SQL supports a special value known as NULL which is used to represent the values of attributes that may be unknown o
4 min read
DBMS | SQL | Question 1
The statement that is executed automatically by the system as a side effect of the modification of the database is (A) backup (B) assertion (C) recovery (D) trigger Answer: (D) Explanation: Triggers are the SQL codes that are automatically executed in response to certain events on a particular table. These are used to maintain the integrity of the
1 min read
DBMS | SQL | Question 2
Which of the following command is used to delete a table in SQL? (A) delete (B) truncate (C) remove (D) drop Answer: (D) Explanation: drop is used to delete a table completelyQuiz of this Question
1 min read
SQL Query to Find Number of Employees According to Gender Whose DOB is Between a Given Range
Query in SQL is like a statement that performs a task. Here, we need to write a query that will find the number of employees according to gender whose DOB is in the given range. We will first create a database named “geeks” then we will create a table “department” in that database. Creating a Database : Use the below SQL statement to create a datab
2 min read
Working With JSON in SQL
JSON stands for Javascript Object Notation. It is mainly used in storing and transporting data. Mostly all NoSQL databases like MongoDB, CouchDB, etc., use JSON format data. Whenever your data from one server has to be transferred to a web page, JSON format is the preferred format as front-end applications like Android, iOS, React or Angular, etc.,
7 min read
Dirty Read in SQL
Pre-Requisite - Types of Schedules, Transaction Isolation Levels in DBMS A Dirty Read in SQL occurs when a transaction reads data that has been modified by another transaction, but not yet committed. In other words, a transaction reads uncommitted data from another transaction, which can lead to incorrect or inconsistent results. This situation can
6 min read
QUOTENAME() Function in SQL Server
QUOTENAME() function : This function in SQL Server is used to return a Unicode string with delimiters added in order to make the string a valid SQL Server delimited identifier. Features : This function is used to find a Unicode string with delimiters added. This function accepts only strings and delimiters. This function add delimiters by default i
3 min read
Article Tags :