0% found this document useful (0 votes)
47 views10 pages

Untitled

Common table expressions (CTEs) allow for temporary results sets that exist only during query execution, and can make code more readable and queries more performant; CTEs can be either recursive, referencing themselves to repeatedly iterate over data, or non-recursive; The document discusses the syntax, advantages, and limitations of both recursive and non-recursive CTEs as well as more advanced CTE concepts like multiple and nested CTEs.

Uploaded by

MOHAN R
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
47 views10 pages

Untitled

Common table expressions (CTEs) allow for temporary results sets that exist only during query execution, and can make code more readable and queries more performant; CTEs can be either recursive, referencing themselves to repeatedly iterate over data, or non-recursive; The document discusses the syntax, advantages, and limitations of both recursive and non-recursive CTEs as well as more advanced CTE concepts like multiple and nested CTEs.

Uploaded by

MOHAN R
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

DAY 7

 Common Table Expression


Advanced SQL
 Recursive CTE
Common Table Expression
A CTE (Common Table Expression) is a one-time result set that only exists for the duration of the query.
It allows us to refer to data within a single SELECT, INSERT, UPDATE, DELETE, CREATE VIEW, or MERGE
statement's execution scope. It is temporary because its result cannot be stored anywhere and will be lost as
soon as a query's execution is completed.

A DBA always preferred CTE to use as an alternative to a Subquery/View.

Syntax :

WITH cte_name (column_names)


AS (query)
SELECT * FROM cte_name;

Reference: https://docs.microsoft.com/en-us/sql/t-sql/queries/with-common-table-expression-transact-
sql?view=sql-server-ver15
Continue..
We cannot use the following clauses in CTE:

• ORDER BY unless you also use as TOP clause


• INTO
• OPTION clause with query hints
• FOR BROWSE

Some of its advantages are given below:

• CTE facilitates code maintenance easier.


• CTE increases the readability of the code.
• CTE increases the performance of the query.
• CTE makes it possible to implement recursive queries easily.

Types of CTE in SQL Server :

SQL Server divides the CTE (Common Table Expressions) into two broad categories:
1. Recursive CTE
2. Non-Recursive CTE
Recursive CTE
A common table expression is known as recursive CTE that references itself.
Its concept is based on recursion, which is defined as "the application of a recursive process or definition
repeatedly." When we execute a recursive query, it repeatedly iterates over a subset of the data.
It is simply defined as a query that calls itself. There is an end condition at some point, so it does not call itself
infinitely.
A recursive CTE must have a UNION ALL statement and a second query definition that references the CTE itself in
order to be recursive.

Syntax :

WITH expression_name (column_list)


AS
(initial_query
UNION ALL
recursive_query -- Recursive member that references expression_name.)
-- references expression name
SELECT *
FROM expression_name
Continue..

Example:
OUTPUT
WITH
odd_num_cte (id, n) AS
(
SELECT 1, 1
UNION ALL
SELECT id+1, n+2 from
odd_num_cte where id < 5
)
SELECT * FROM odd_num_cte;
Sample File

CTE.sql
Non-Recursive CTE
A common table expression that doesn't reference itself is known as a non-recursive CTE.
A non-recursive CTE is simple and easier to understand because it does not use the concept of
recursion. According to the CTE Syntax, each CTE query will begin with a "With" clause followed by the
CTE name and column list, then AS with parenthesis.

Limitations of using CTE in SQL Server:

• Recursive CTE members are unable to use the keyword clauses like Distinct, Group By, Having, Top,
Outer Joins.
• The CTE can only be referenced once by the Recursive member.
• We cannot use the table variables and CTEs as parameters in stored procedures.
• Since it's just a shortcut for a query or subquery, it can't be reused in another query.
• The scope of CTE is limited and thump rule. Means it will be available to use in immediate statement
only.
• The number of columns in the CTE arguments and the number of columns in the query must be the
same.
• We cannot perform UPDATE, INSERT, DELETE on a CTE in Azure SQL
Multiple CTEs
• Multiple CTEs are many CTEs in a single query. These CTE are separated by comma and commas
should not be given at the end of the last CTE.
• The WITH keyword will be mentioned only once during the start of the CTE definition. This comma-
separated multiple CTE makes sense when we must refer to the return of one CTE in another CTE
and so on.
• For multiple CTE we need to do set-based operations like UNION, UNION ALL, etc.
Nested CTEs
• Like Subqueries we can't define CTE inside CTE. But we can refer to the previously defined CTE in
subsequent CTEs in the FROM clause.
• Nested CTEs are more useful in cases where we need to compute aggregate functions on several
levels and to compare two or more grouping of rows.
Exercise
• What is the difference between Common Table Expression and Derived Table and SubQuery?
• Can you use a CTE in the WHERE clause?
• Can you DELETE the records from the CTE? Does it also affect the actual underlying base
table?
• How can you get the third-highest salary using the CTE?
• How can you check and remove the duplicate records using the CTE? Demonstrate in Azure.
• How can you apply multi-level aggregations in SQL?

SQL exercises on DERIVED TABLES AND CTES (wiseowl.co.uk)

You might also like