In this lesson, you will learn how to use Common Table Expressions (CTEs) to transform messy, deeply nested queries into clean, readable segments of logic.
The Problem with Subqueries
Up until now, when you needed to perform a multi-step calculation, you likely used subqueries inside your FROM or WHERE clauses. While effective, subqueries can quickly become "spaghetti code." If you nest a subquery inside a subquery, it becomes difficult for humans (and sometimes the database engine) to follow the flow of logic.
Enter the CTE
A Common Table Expression, or CTE, acts like a temporary named result set that exists only for the duration of a single query. You define it at the very top of your statement using the WITH keyword. Think of it as breaking a long, complex math problem into simple, named steps.
Consider a scenario where you first want to find the total sales per department, and then filter for departments with sales over $10,000:
WITH DepartmentSales AS (
SELECT department_id, SUM(amount) AS total_revenue
FROM sales
GROUP BY department_id
)
SELECT department_id, total_revenue
FROM DepartmentSales
WHERE total_revenue > 10000;
Why Use This?
- Readability: By giving your sub-step a name (like
DepartmentSales), you tell the reader exactly what that part of the data represents before they even see the code. - Maintenance: If you need to change your calculation, you only edit the specific block inside the
WITHclause, rather than hunting through layers of parentheses. - Flow: It forces you to write code from top to bottom, mirroring how we read, rather than inside-out.
Even if you are only performing one calculation, using a CTE makes your intent clear and provides a "staging area" for your data before the final projection. It turns complex queries into a series of logical, manageable building blocks.
Key Takeaway: Common Table Expressions allow you to break complex queries into named, modular segments that improve code readability and simplify logic flow.