Common Table Expression (CTE) in SQL offers a more readable form of a derived table. A Common Table Expression is an expression that returns a temporary result set. This result set is similar to a hybrid Derived Table. The resultset can be declared once and referenced multiple times in a query. It does not require any extra effort to declare it. CTE is more powerful than the derived table. It can self-reflect, and we can also use CTE multiple times in the same query. Mainly, CTE improves readability and makes it easy to maintain complex queries. CTE can be used for selects, and DML (Insert, Update, and Delete) statements.
Common Structure of CTE
The Common Table Expression is created using the WITH statement followed by the CTE name and List of Columns (specifying a column is optional). After the "AS," the information used to populate the returning columns begins. The CTE is then followed by a select calling it. Always start CTE with a semi-colon.
Example
Step 1. Create a query
The following is a sample of creating two tables, EmployeeMasters and DepartmentMasters, and inserting some default values into them.
Step 2. Writing CTE Query
The following is a sample use of a CTE Query.
When to Use CTE in SQL?
CTE offers the same functionality as a View (ideal for one-off usages). CTE provides the following four advantages.
- Create a recursive query.
- Alternative from a view when the general use of an idea is not required, a case in which you do not have to store the definition in metadata.
- Enable grouping by a column derived from a scalar subselect or a function that is either not deterministic or has external access.
- Reference the resulting table multiple times in the same statement.
CIt can not use with CTE
- The clauses like ORDER BY, INTO, OPTION clause with query hints, FOR XML, and BROWSE cannot be used in the CTE query definition.
- "SELECT DISTINCT," GROUP BY, PIVOT, HAVING, Scalar aggregation, TOP, LEFT, RIGHT, OUTER JOIN, and Subqueries "are not allowed in the CTE query definition of a recursive member.
- A CTE can be self-referencing and previously defined CTEs in the same WITH clause. Forward referencing is not allowed.
- Specifying more than one "WITH" clause in a CTE is prohibited. For example, if a CTE query definition contains a subquery, then that subquery cannot have a nested WITH clause to define other CTE.
Summary
CTE provides a more readable and usable approach to derived tables. CTE is not materialized into a work table (temporary table). CTEs are not a replacement for temporary Tables. The scope of the CTE is limited to the first SELECT statement only.
HostForLIFEASP.NET SQL Server 2019 Hosting