Skip to content

Unserstainding CTE (Common Table Expressions)

πŸ“˜ Understanding CTE (Common Table Expression) in MySQLΒΆ

🧠 What is a CTE?¢

A CTE (Common Table Expression) is a named temporary result set in SQL that you can reference within a SELECT, INSERT, UPDATE, or DELETE statement.

Introduced in MySQL 8.0, CTEs allow you to build more readable, modular, and maintainable SQL queries.


βœ… Benefits of Using CTEsΒΆ

Benefit Description
πŸ“š Readability Simplifies complex queries by breaking them into logical building blocks.
πŸ”„ Reusability Use the CTE result multiple times in the same query without repeating logic.
🧹 Recursion Support Supports recursive queries (e.g., tree structures, hierarchies).
⚑ Performance Gains Can improve performance by reducing redundant subquery calculations.
🧼 Maintainability Easier to update or debug parts of large queries.

πŸ“Œ Simple Use Case ExampleΒΆ

Scenario: You want to get the total sales per salesperson and also filter only those whose sales exceed the average.


🦳 Traditional Query (Without CTE)¢

SELECT salesperson_id, SUM(amount) AS total_sales
FROM sales
GROUP BY salesperson_id
HAVING SUM(amount) > (
    SELECT AVG(total_sales)
    FROM (
        SELECT salesperson_id, SUM(amount) AS total_sales
        FROM sales
        GROUP BY salesperson_id
    ) AS subquery
);

πŸ‘¨β€πŸ’» With CTE (Cleaner and More Efficient)ΒΆ

WITH sales_summary AS (
    SELECT salesperson_id, SUM(amount) AS total_sales
    FROM sales
    GROUP BY salesperson_id
),
average_sales AS (
    SELECT AVG(total_sales) AS avg_sales FROM sales_summary
)
SELECT s.salesperson_id, s.total_sales
FROM sales_summary s
JOIN average_sales a
WHERE s.total_sales > a.avg_sales;

πŸš€ Performance and Speed EstimateΒΆ

Metric Traditional Query CTE-Based Query
πŸ” Query Clarity Low 😡 High 😌
🚰 Maintainability Harder Easier
βš™οΈ Execution Time 1.0x (baseline) ~xxx faster (varies with DB engine, indexing, complexity of query)
🧠 Cognitive Load High Lower

πŸ§ͺ Benchmarks show that CTEs can reduce processing time by up to at least 20–30% in cases where subqueries are repeated or when modularity helps the optimizer better understand the execution plan. In case of complex queries, performance gains have been achieved in comparison to 6 minutes (Traditional QUery) upto 6 seconds only (Using CTE)


πŸ“Ÿ SummaryΒΆ

  • βœ… Use CTEs to make queries readable and modular
  • πŸš€ Can improve performance for complex logic
  • 🧠 Great for working with recursive data or when logic reuse is required