Is SQL or even TSQL Turing Complete?

It turns out that SQL can be Turing Complete even without a true ‘scripting’ extension such as PL/SQL or PSM (which are designed to be true programming languages, so that’s kinda cheating).

In this set of slides Andrew Gierth proves that with CTE and Windowing SQL is Turing Complete, by constructing a cyclic tag system, which has been proved to be Turing Complete. The CTE feature is the important part however — it allows you to create named sub-expressions that can refer to themselves, and thereby recursively solve problems.

The interesting thing to note is that CTE was not really added to turn SQL into a programming language — just to turn a declarative querying language into a more powerful declarative querying language. Sort of like in C++, whose templates turned out to be Turing complete even though they weren’t intended to create a meta programming language.

Oh, the Mandelbrot set in SQL example is very impressive, as well 🙂

Leave a Comment