You are on page 1of 5

What is CTE in SQL?

CTE is the short form for Common Table Expressions. It is the concept of SQL
(Structured Query Language) used to simplify coding and help to get the result as
quickly as possible. CTE is the temporary table used to reference the original table.
If the original table contains too many columns and we require only a few of them,
we can make CTE (a temporary table) containing the required columns only.

Creating and Using CTE in SQL

Syntax of CTE
WITH CTE_NAME AS
(
SELECT column_name1, column_name2,..., column_nameN
FROM table_name
WHERE condition
)
SELECT column_name1, column_name2,..., column_nameN
FROM CTE_NAME;

Querying with CTEs

1. Selecting data from CTEs


After defining a CTE, you can select data from it using a standard SELECT
statement:

2. Inserting, updating, and deleting data using CTEs

-- Insert
INSERT INTO target_table

SELECT ... FROM CTE_name ...

-- Update

UPDATE target_table

SET ...

FROM CTE_name

WHERE ...

-- Delete

DELETE target_table

FROM target_table

JOIN CTE_name ON …

Chaining Multiple CTEs


WITH

CTE1 AS (SELECT ...),

CTE2 AS (SELECT ... FROM CTE1 ...),

CTE3 AS (SELECT ... FROM CTE2 ...)


SELECT ... FROM CTE3 ...;

Types of CTEs in SQL

1. Non-Recursive CTEs

Non-Recursive CTEs are used to simplify complex queries and improve code
readability. They serve as a temporary result set, allowing developers to break
down and organize various parts of the query logically, which can be referenced
later within the same query.

Real-life examples

 Aggregating sales data from multiple tables, making it easier to calculate


KPIs and metrics.
 Filtering and transforming data before joining it with other tables, improving
query performance and readability.

2. Recursive CTEs

Recursive CTEs enable querying hierarchical or iterative data structures,


such as parent-child relationships, tree traversal, or finding the shortest path
in a graph. They consist of an initial, non-recursive part (called anchor
member) and a recursive part (called recursive member), which references
the CTE itself.

Real-life examples

 Retrieving the entire hierarchy of employees and their managers in an


organization.
 Finding the shortest path between two nodes in a transportation network or
the least number of steps to solve a puzzle.

CTE in SQL vs. Other Techniques

1)Comparing CTEs with subqueries

CTEs can improve readability and maintainability in complex scenarios. In some


cases, the query optimizer might generate better execution plans for CTEs,
resulting in faster performance.

 Use CTEs for simplifying large queries, breaking them into smaller, more
readable parts, or when the same subquery is used multiple times within the
query.
 Use subqueries for single-use, simple, or correlated operations that don’t
benefit from CTE’s modularity.

2)Comparing CTEs with temp tables

CTEs are temporary result sets, used for readability and maintainability, existing
only for the scope of a single query. They are not stored in the database whereas
Temp tables are physical tables stored temporarily in the database, allowing
indexing, modification, and access across multiple queries within the same session.

Advantages of Using CTEs


 CTEs break down complex queries into smaller, more manageable parts. By
naming each part and isolating it within a CTE, developers can easily
understand the purpose of each component and the overall query logic,
making the code more readable

 As CTEs improve readability, they also make the code easier to maintain.
When updating or modifying a query, developers can quickly identify the
relevant CTEs and make changes without affecting the rest of the query.

 CTEs allow developers to encapsulate specific portions of a query’s logic,


promoting a modular approach to query design. This abstraction not only
makes the query more maintainable but also promotes code reusability, as
the same CTE can be referenced multiple times within a query, reducing
code duplication.

You might also like