It’s not just CTE, it’s all SQL. SQL is a language (not programming as some think) declarative, IE, you say what you want and is the problem of engine who’s behind her working it out the best way he can. So he sort of interprets what his code wants and tells the computer to run, unlike most traditional programming languages that are imperative the code says more exactly what to do than it wants.
Just making it clear that more imperative codes can become somewhat declarative, from simple abstraction to stronger syntax and abstractions that really change the way you do it all.
So in a way it has a loop yes, but well in a way, because the way it performs is the problem of engine And if you think about it, the concept of a loop is already abstract, a computer doesn’t understand that, so there’s a repetition of execution, as happens all the time in everything that you do and you’re not even noticing. Somehow this will be interpreted and executed through a rather complex repetition.
The SELECT
simple will already make a "loop" somehow in most cases (the first is one that won’t do it, doesn’t have multiple data to evaluate). This CTE itself has no tie, what’s in it is that it has.
That’s why I tell people to learn how the computer works, how the computer works, how deep, and then going up the abstractions on top of it, this gives a very big force to program well. I do not believe in programmers who do not know this, even some experienced and who are considered good by many, if you do not know this I guarantee that they are overvalued, at least more than they should.
By completing the @Maniero response, always remember to search which database you are applying to CTE. Each engine of each bank works in one way and the performance can vary greatly may, in some cases, not be the best output using CTE’s.
– Thiago Araújo
@Douglasvieira The code you posted is an example of recursive CTE.
– José Diz