What is the difference between common table expressions and recursive common table expressions?
Last updated
A plain CTE is a one-shot named subquery that runs once; a recursive CTE references itself and iterates, making it the tool for problems of unknown or variable depth.
Ordinary CTE:
A readability/structuring aid: factor a subquery out and reference it, possibly multiple times.
Evaluated a single time, no self-reference.
Recursive CTE:
Requires the
RECURSIVEkeyword (in most engines) and an anchor + self-referencing member joined byUNION ALL.Loops until the recursive member yields no rows.
Shared trait: both are scoped to the statement they precede and don't persist like a view.
Practical difference: a normal CTE can't traverse an arbitrarily deep tree; a recursive one can.
- https://skphd.medium.com/sql-window-functions-interview-questions-and-answers-127ee0be483b
- https://medium.com/@shreyassn/120-sql-interview-questions-db85e4304ffd
- https://www.foundit.in/career-advice/20-common-sql-interview-questions-answers/
- https://medium.com/@Ishan.tharusha.wijayabahu/top-50-essential-sql-interview-questions-for-software-engineers-in-2024-8da12396f199
- https://interviewkickstart.com/blogs/interview-questions/sql-interview-questions
- https://medium.com/data-engineer/recursive-ctes-in-sql-7b5dc666b16a
- https://codewiz.info/blog/sql-common-table-expressions/
- https://www.dbvis.com/thetable/a-complete-guide-to-the-mysql-cte-mechanism/