Updated March 13, 2023
Introduction to SQL CTE
Common table expression (CTE) was introduced in the SQL server 2005 and it is a temporary named result set. It is characterized by a simple query and defined within the execution scope of a single SELECT, INSERT, UPDATE, DELETE or MERGE statement. We can also use CTE for CREATE VIEW statement which is a subset of the SELECT statement. A typical CTE articulation can incorporate references to itself.
The following shows the common syntax of a CTE in SQL Server:
WITH expression_name[(column_name [,...])] AS (CTE_definition) SQL_statement;
In the above expression:
- Step one, we need to specify (expression_name) the name of the expression to which will be later used by the query. Expression name is similar to a table name when we create a table.
- Next, after expression_name we determine a rundown of column name which is separated by a comma and the definition. The count of columns in expression_name and count of columns defined in the CTE_definition must be equal.
- After that, we use the keyword “AS” before CTE_definition and if only expression name is given then all columns from the CTE_definition will be added.
- Subsequently, make a definition of a SELECT statement whose result set is passed the CTE.
- At last, refer to the CTE in a query such as INSERT, SELECT, DELETE, UPDATE, or MERGE.
Guidelines for Creating and Using CTE
- After declaring CTE there should be a single SELECT, UPDATE, INSERT or DELETE and it can also be specified as part of CREATE VIEW statement.
- A non-recursive CTE can define query definitions with multiple CTE and the result should be merged by one of these operators: UNION ALL, UNION, INTERSECT, or EXCEPT.
- A reference to the CTE can be made within the same WITH clause.
- Indicating more than one WITH condition in a CTE isn’t permitted. For instance, if a CTE_query_definition contains a subquery, that subquery can’t contain a settled WITH statement that characterizes another CTE. You cannot use following clauses in CTE_definition
- ORDER BY
- FOR BROWSE
- On the off chance that CTE is a part of a batch, then there should be a semicolon at the end
- A cursor can be defined by referring to a CTE.
- A CTE can reference tables from the remote servers.
Guidelines for Creating and Using Recursive CTE
- A definition of recursive CTE must consist of at least two CTE query definitions, an anchor member, and a recursive member. Anchor member query must be before recursive members.
- The anchor and the recursive members must have the same number of columns.
Common Table Expression in SQL Examples
Starting with some basic examples of using Common table expressions:
Example #1 – Simple CTE Example in SQL Server
CTE is used by this query to return Department id
WITH cte_dept AS ( select * from HumanResources.Department ) select DepartmentID from cte_dept
Explanation: This is the most basic example in which step one is to define cte_dept as the name of the common table expression. This CTE returns the result which consists of all the columns of the Department table from the query definition as we have not specified any columns.
Second, we created a query that gives all the columns from the Department table. The third step is to use the CTE in the outer query and only select DepartmentIDfrom the CTE.
Example #2 – Simple SQL Server CTE Example with column names
WITH cte_deptName(DepartmentName,DepartmentGroupName) AS ( select Name,GroupName from HumanResources.Department ) select DepartmentName from cte_deptName
Explanation: First, we defined cte_deptName as the name of the CTE. This CTE returns the result which consists of all the columns of the Department table from the query definition and we have specified the column names.
Second, we created a query that gives Name, GroupName columns from the Department table. The third step is to use the CTE in the outer query and only select DepartmentName from the CTE.
Example #3 – Using multiple SQL Server CTE in a single query
WITH cte_deptName(DepartmentID,DepartmentName) AS ( select DepartmentID,Name from HumanResources.Department ), cte_deptGroup(DepartmentID,DepartmentGroupName) AS ( Select DepartmentID,GroupName from HumanResources.Department ) Select DepartmentName from cte_deptNamed N INNERJOIN cte_deptGroup dG ON dN.DepartmentID=dG.DepartmentID
Explanation: First, we defined cte_deptName as the name of the common table expression. This CTE returns the result which consists of all the columns of the Department table from the query definition and we have specified the column names and then we have similarly defined cte_deptGroupwhich as a comma-separated
Second, we created a query whichgivesDepartmentID, Name columns from the Department table for first CTE and DepartmentID, GroupName for second CTE
The third step is to use the CTE in the outer query and only selectDepartmentNamefrom the inner join of CTE using DepartmentID.
Why Do you Need CTE?
There e several other methods like creating views, temporary tables, or derived tables to achieve the same result then why do we use CTE? There are several reasons and some of them are as follows:
- Readability: CTE enhances readability as rather than lumping all the logic of query into one huge query, we create several CTE’s which is later combined in a statement. So, all the chunks of data can be combined into the final select statement.
- Substitute for a View: Views can be substituted for a CTE. There may be several reasons for this like for example you do not have the permission to create a view or you have to use it just one time and do not want to save it for later use.
- Recursion: CTE’s can be used to perform recursive queries. These are the queries that call themselves and can be used in hierarchical data such as organizational chart.
- Limitations: Since SELECT statement cannot reference itself or do GROUP BY using non-deterministic functions that are overcome by CTE.
We hope that this EDUCBA information on “SQL CTE” was beneficial to you. You can view EDUCBA’s recommended articles for more information.