What are Common Table Expression(CTE) with Examples?

Advanced SQL is used frequently. At least the word “advanced” is. Both SQL users and SQL trainees utilize it frequently. It is mentioned in the descriptions of SQL courses, job postings, and interview questions. The SQL literature contains it. When coworkers are conversing at work, you may hear it. In this article We will discuss about Common Table Expression(CTE) with real life industry examples.

What is Common Table Expression (CTE) ?

The result set of a query that exists only temporarily and is intended to be used in
conjunction with another, larger query is known as a Common Table Expression (CTE).
Similar to a derived table, the output of a CTE is not saved and persists only while the
query is running.

HOW TO CREATE Common Table Expression (CTE) ?

It specifies a common table expression, often known as a temporary named result set (CTE). It is the result of a simple query, specified within the execution scope of a single SELECT, INSERT, UPDATE, DELETE, or MERGE statement. Defining a CREATE VIEW statement A SELECT statement can also contain this clause. Common table expressions are allowed to make references to themselves. Below are the steps to create CTE,

  1. Always start CTE using WITH
  2. Give the soon-to-be-defined result query a name.
  3. After the name is assigned follow with AS
  4. Create the query so it returns the desired set of results.
  5. If more than one CTE is needed, repeat steps 2-3 and start each additional
    expression with a comma.

SYNTAX FOR CTE:
WITH
expression_name_1 AS
(CTE query definition 1)
[, expression_name_X AS
(CTE query definition X)
, etc ]
SELECT expression_A, expression_B, …
FROM expression_name_1

TYPES OF CTE IN SQL
Basically there are two types of CTE

  1. Recursive Common Table Expression
  2. Non – Recursive Common Table Expression
Common Table Expression
Common Table Expressions

RECURSIVE COMMON TABLE EXPRESSION :

A recursive common table is a CTE that references itself or calls itself recursively. This causes the CTE to execute repeatedly, returning subsets of the data, until the full result set of data is returned. A recursive common table expression has anchor and recursive elements within a simple query. First, we need to declared an integer variable as ‘RowNo’, set the default value to 1, and create the first CTE query with the expression name ‘ROWCTE’. This CTE first displays the default line number, then uses union ALL to increment the line number by 1 until the line number reaches the incremented value of 10. To view the results, use the query of your choice to view his CTE results.

SQL Query :

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;

NON – RECURSIVE COMMON TABLE EXPRESSION :

A CTE that does not make internal references to itself is said to be non-recursive. Non-recursive CTEs tend to be simpler than recursive CTEs, so start with this type. According to the CTE Syntax, every CTE question will start with a “With” clause observed through the CTE call and column list, then AS with parenthesis.

ADVANTAGES AND DISADVANTAGES OF CTE :

Advantages of CTE :

  1. The primary benefit of CTE is its advanced code clarity in comparison to the
    subquery approach.
  2. It can be referred multiple times in a query.
  3. Because of the recursive programming in CTEs, they are especially effective
    when querying tree-structured data.
  4. It can also be recursive.
  5. The function of CTE is same as database but it stores the definition in metadata

Disadvantages of CTE :

  1. In query like function or view the CTE cannot be reused.
  2. CTE is just the shortcut of a query or subquery. It is also one of the reasons in
    which it cannot be reused like others.
  3. Nested view is not possible in CTE.
  4. Performance issue.
  5. There will be a crash in the server due to infinite loop only when the recursion
    limit exceeds by 32767.

WHEN AND WHERE TO USE CTE?

CTEs are very useful whenever you need to organize complex and long queries. From a functionality and performance perspective, there is no difference between subqueries and CTEs, but using CTEs improves the readability of your code by breaking it into separate steps. This makes troubleshooting easier and makes code easier to modify. CTEs are great when you need recursive data access. If we want to fetch the statistics a couple of times, then we have to now no longer use CTE because of its constrained scope of execution, due to the fact we can should outline CTE on every occasion and that may be expensive. In this case, a transient desk is probably the maximum appropriate option.

Need for CTE?

In SQL, we can join or filter the records from a sub-query by using sub-queries. Every time we use the same data or the same sub-query to connect the same records, we run into maintainability problems. Additionally, there are alternatives in SQL called Derived Tables, Temporary Tables, and Temporary Variables that resemble CTE somewhat, however each has its own set of drawbacks in comparison to CTE. Common Table Expression displays its worth with increased readability and easier maintenance. If you like this article or if you have any issues with same kindly comment in comments section.

Leave a Reply

Your email address will not be published. Required fields are marked *