In the previous tutorial, we learned how Subqueries can be used to compare query results without using multiple joins. However, when using multiple Subqueries, it can become very difficult to see where one Subquery ends and another begins. Enter the Common Table Expression (CTE). This tutorial will cover the following learning objectives:
When writing complex queries, it may be tempting to use multi-nested Subqueries in the WHERE Clause. However, this makes it much more difficult to read the query. Common Table Expressions (CTEs) help solve this problem. Watch the following videos to better understand this concept:
Now that you have a basic understanding of when to use a CTE, let's learn how to write one. Watch the following video to get a better understanding of this concept:
WITH [alias] AS (
SELECT [col1], [col2]
FROM [table_name]
WHERE [list of conditions]
)
SELECT *
FROM [cte_alias]
WHERE [list of conditions];
WITH [alias1] AS (
SELECT [col1], [col2]
FROM [table_name]
WHERE [list of conditions]
),
[alias2] AS (
SELECT [col1], [col2]
FROM [alias1]
WHERE [list of conditions]
)
SELECT *
FROM [cte_alias]
WHERE [list of conditions];
Although we have already covered some of the common use cases behind CTEs, let's dive deeper into why they are preferred over Subqueries. Watch the following video to get a better understanding of this concept:
Congratulations! You just completed the Common Table Expressions (CTEs) Tutorial! To help test your knowledge, let's
complete the same questions as the previous exercise, but using CTEs rather than Subqueries. This exercise is based on
the exercise of the previous tutorial.
**It's highly recommended that you
complete the exercise outlined in the previous tutorial before beginning this exercise.**
Have any issues with the above exercise? Post your question on Discord!