A Common Table Expression (CTE) is a temporary, named result set defined within the execution scope of a single SQL statement (SELECT, INSERT, UPDATE, or DELETE). Introduced in MySQL 8.0, CTEs use the WITH keyword and dramatically enhance query readability, modularity, and maintainability compared to nested derived tables (subqueries).
The Problem with Nested Derived Subqueries
Consider a query that calculates department salary metrics and joins those metrics back to employee details:
1-- Nested derived table approach: Hard to read and maintain
8)AS dept_stats ON e.department_id = dept_stats.department_id
9WHERE e.salary > dept_stats.avg_sal;
When subqueries are nested 3 or 4 layers deep, code readability plummets. CTEs eliminate this nesting by declaring intermediate result sets at the top of the statement.
Single Query Scope: A CTE exists only during the execution of the statement that defines it. As soon as the query returns results, the CTE is discarded from memory.
DML Compatibility: CTEs can be used preceding INSERT INTO ... SELECT, UPDATE ... JOIN CTE, and DELETE ... USING CTE statements in MySQL 8.0+.
Optimization: MySQL 8.0's optimizer determines whether to merge the CTE inline or materialize it into an in-memory temporary table for optimal execution speed.
Interactive Quiz• Knowledge Check
Multiple Choice Questions
Question 1
Which SQL keyword introduces a Common Table Expression?
Question 2
In which MySQL version were Common Table Expressions (CTEs) officially introduced?
Question 3
What is the lifespan of a Common Table Expression?
Question 4
What is a major readability advantage of CTEs over nested derived subqueries?
Question 5
Can a CTE be referenced in an INSERT or UPDATE statement?
Next Lesson
Chaining Multiple CTEs in a Single Query
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.