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 [,...])]
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 batch, then there should be a semicolon at the end
- A cursor can be defined by referring to a CTE.
- A CTE can reference table 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 expression:
Example #1 – Simple CTE Example in SQL Server
CTE is used by this query to return Department id
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 Department table from the query definition as we have not specified any columns.
Second, we created a query which 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
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 column of Department table from the query definition and we have specified the column names.
Second, we created a query which 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
select DepartmentID,Name from HumanResources.Department
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 column of Department table from the query definition and we have specified the column names and then we have similarly defined cte_deptGroupwhich is 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?
Their 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 chunk 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.
This is a guide to SQL CTE. Here we also discuss the introduction and guidelines for creating and using cte along with different examples and its code implementation. you may also have a look at the following articles to learn more –