MySQL + SQL · Lesson 77
CTE and WITH Clause in MySQL
What is a CTE?
A CTE (Common Table Expression) is a temporary named result defined with
WITH, used to make complex queries readable. MySQL 8+.Example
WITH high_scorers AS (
SELECT name, marks FROM students WHERE marks >= 90
)
SELECT * FROM high_scorers ORDER BY marks DESC;The CTE "high_scorers" is defined once and used like a table in the main query.
Why Use CTEs?
- Break a big query into readable named steps.
- Reuse the same subquery result multiple times.
Summary
- A CTE is a named temporary result defined with WITH.
- Makes complex queries cleaner and more readable.
💻 Live Code Editor
This page's programs are ready here — run them, edit them, and learn. No installation needed.
Powered by OneCompiler. The code loads into the editor automatically — press Run to see the output. If the editor does not open, open it in a new tab.