What are CTE's in SQL
WITH Statements?
What the benefits, limitations and Syntax are
https://www.selectdistinct.co.uk/2023/12/05/how-to-use-a-cte/
#SQL #CTE #SQLWITH #DATA
2. CTEs in SQL are a way to simplify code by creating a temporary dataset, giving it a
name, then referencing that dataset later in your query
Also known as the WITH clause
3. Syntax of the CTE in SQL
WITH Merged as
(
SELECT [Product_ID], [Store_ID], [qty_sold] from SalesA
union
SELECT [Product_ID], [Store_ID], [qty_sold] from SalesB
)
SELECT * from Merged
‘WITH’ is the start, followed by the name of
the data set
Then within brackets goes the SQL code for
the dataset
Finally you can call it as you would a
table or subquery
4. Benefits of CTEs
Simplicity
simplify complex queries and improve their readability
Performance
improve query performance by breaking down complex
queries into smaller, more manageable parts
5. Limitations of CTEs
Limited Scope
Can only be utilized within a SELECT, INSERT, UPDATE, or
DELETE statement
Memory Usage
can consume a lot of memory
Performance
can sometimes be slower than other methods, such as
temporary tables
6. Recursive Queries
WITH CTE
AS
(
SELECT cast(GETDATE()AS date) AS [date]
UNION ALL
SELECT DATEADD(dd, 1, [date])
FROM CTE
WHERE DATEADD(dd, 10, [date])
< CAST('2023-12-31' as date)
)
SELECT [date] FROM CTE
We can use a recursive CTE to refer back to itself in a loop
Here we see a list of dates, between today and fixed end date
7. CTEs are used for a variety of reasons, including simplifying complex queries,
improving query performance, and making queries more readable.
They are also useful for breaking down complex queries into smaller, more
manageable parts.
8. For more Tips, Tricks and
Timesavers, visit our website
Business Analytics Blog – Select Distinct
Credit: simon.harrison@selectdistinct.co.uk