Intermediate Topic 34 of 51 Databases
Common Table Expressions
Named temporary result sets within a query.
How it works
A common table expression, introduced with WITH, defines a named temporary result set that can be referenced in the main query, making complex SQL readable by breaking it into steps. Several CTEs can be chained, and recursive CTEs reference themselves to traverse hierarchies and graphs, with an anchor member and a recursive member combined by UNION ALL. Some databases materialize CTEs, while others inline them.
Step-by-step walkthrough
- A CTE gives a name to a subquery with WITH.
- The named result can be used like a table.
- The main query reads from it, maybe several times.
- It makes long queries readable.
- Recursive CTEs walk hierarchies such as org charts.
Where it is used
Organizational charts, bills of materials, category trees, generating series of dates, and splitting long reports into understandable pieces use CTEs.
Common pitfall
Assuming a CTE is always cached or always inlined can cause performance surprises, depending on the database and version. Recursive CTEs without a termination condition loop forever or hit recursion limits, especially with cyclic data. Reusing a CTE many times may recompute it. Check the plan and use temporary tables if needed.
Where it fits in the course
Common Table Expressions is topic 34 of 51 in Databases, rated Intermediate. It follows Window Functions. The next topic is Recovery and Logging.
Practice and explore
- Open the interactive lesson, with a mini quiz.
- Take the Databases quiz.
How to study this topic
- Read the explanation above and restate the definition in your own words.
- Open the interactive lesson and answer its mini quiz.
- Read the common pitfall, then write a short example that avoids it.
- Check your understanding in the Databases quiz, and revisit the topic if you miss a question.
Frequently asked questions
What is Common Table Expressions?
Where do people use Common Table Expressions?
What is the most common mistake with Common Table Expressions?
What should I learn before this topic?
How can I practice it?
Is Common Table Expressions hard to learn?
How long does it take to learn Common Table Expressions?
Which topics are related to Common Table Expressions?
What should I study after Common Table Expressions?
Related topics
- Window Functions (Databases)
- Recovery and Logging (Databases)
- Query Execution Plans (Databases)
- Database Partitioning (Databases)
- Expressions (Programming Fundamentals)
- Regular Expressions in Theory (Theory & Discrete Math)
- Longest Common Subsequence (Algorithms)