Professional Documents
Culture Documents
CTE in SQL
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.
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;
-- Insert
INSERT INTO target_table
-- Update
UPDATE target_table
SET ...
FROM CTE_name
WHERE ...
-- Delete
DELETE target_table
FROM target_table
JOIN CTE_name ON …
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
2. Recursive CTEs
Real-life examples
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.
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.
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.