Learn Common Table Expressions (CTE) in SQL

What are CTEs?

Common Table Expressions (CTEs) are temporary result sets defined within a SELECT statement. They provide a way to break down complex queries into smaller, more manageable parts. Think of them as temporary tables that exist only within the scope of the main query. Defined using the WITH clause, CTEs are used within the query they're created in, offering a cleaner and more organized approach compared to subqueries.

Why Use CTEs?

  • Improved readability: They make complex queries easier to understand by breaking them down into logical steps.
  • Enhanced maintainability: Changes to the CTE can be made independently without affecting the entire query.
  • Recursive queries: CTEs are essential for implementing recursive algorithms, such as calculating hierarchies or generating sequences.
  • Reusability: Once defined, a CTE can be referenced multiple times within the same query, reducing repetition.

Example of a Simple CTE

Let’s say you have a Sales table, and you want to find the total sales for each salesperson but only for those who achieved sales above a certain threshold. You can use a CTE to make this query more readable.

WITH Sales_CTE AS (
    SELECT SalesPersonID, SUM(SalesAmount) AS TotalSales
    FROM Sales
    GROUP BY SalesPersonID
)
SELECT SalesPersonID, TotalSales
FROM Sales_CTE
WHERE TotalSales > 10000;

Recursive CTEs

Recursive CTEs are an extension of the basic CTE that allows a query to reference itself. This is particularly useful for dealing with hierarchical data.

Here’s an example of a recursive CTE to retrieve an employee hierarchy.

WITH EmployeeHierarchy AS (
    SELECT EmployeeID, ManagerID, Name, 0 AS Level
    FROM Employees
    WHERE ManagerID IS NULL
    UNION ALL
    SELECT e.EmployeeID, e.ManagerID, e.Name, eh.Level + 1
    FROM Employees e
    INNER JOIN EmployeeHierarchy eh ON e.ManagerID = eh.EmployeeID
)
SELECT EmployeeID, Name, Level
FROM EmployeeHierarchy;

In this example, the recursive CTE starts by selecting the top-level managers (those with no ManagerID). It then recursively joins the Employees table to build out the hierarchy, adding a level of depth with each recursive step.

Conclusion

CTEs are essential for writing efficient, maintainable SQL queries. They simplify complex logic, support recursion, and enhance code clarity, making them a valuable tool for any SQL developer. Whether you’re dealing with large datasets or hierarchical data, CTEs offer a structured approach that can make your queries more efficient and easier to understand.


Similar Articles