DEV Community

Cover image for Common Table Expressions
Charity Jelimo
Charity Jelimo

Posted on

Common Table Expressions

A Common Table Expression (CTE) is a temporary result set that simplifies and structures SQL queries. It is defined using the WITH keyword and can improve query readability and reusability. In some cases, CTEs can also enhance performance by avoiding redundant calculations.

What are CTEs?

  1. Temporary Result Set:
    CTEs exist only during the execution of the query and are not stored in the database.

  2. Readability and Maintainability:
    By breaking complex logic into reusable components, CTEs make queries easier to understand.

  3. Reusable Within the Query:
    A CTE can be referenced multiple times within the query, avoiding repeated logic or calculations.

Why use CTEs?

  1. Simplify Complex Queries: Break large queries into smaller, named parts for clarity.
  2. Eliminate Redundant Calculations: Replace repeated subqueries with a single calculation in a CTE.
  3. Improve Maintainability: Centralize repeated logic in one place, making updates easier.
  4. Enable Recursive Queries: Handle hierarchical or iterative data using recursive CTEs.

How Do CTEs Optimize Performance?

  1. Reduce Redundancy: CTEs calculate a result once, reducing unnecessary repetition. Example:
SELECT 
    o.OrderID
FROM Orders o
WHERE o.TotalAmount > (SELECT AVG(TotalAmount) FROM Orders)
  AND o.TotalAmount < (SELECT AVG(TotalAmount) FROM Orders);
Enter fullscreen mode Exit fullscreen mode

Problem: The subquery (SELECT AVG(TotalAmount) FROM Orders) is calculated twice.

Solution Using a CTE:

WITH AvgTotalAmount AS (
    SELECT AVG(TotalAmount) AS AvgAmount
    FROM Orders
)
SELECT o.OrderID
FROM Orders o
JOIN AvgTotalAmount a
WHERE o.TotalAmount > a.AvgAmount
  AND o.TotalAmount < a.AvgAmount;
Enter fullscreen mode Exit fullscreen mode
  1. Simplify Execution Plans:
    With a CTE, the database evaluates the logic once and reuses the result.

  2. Readable Performance Gains:
    Even if there’s no computational gain, a CTE often makes execution plans easier to debug.

Top comments (0)