We have all seen SQL pushed past its comfort zone to build things like 3D renderers or cellular automata. Naturally, I wondered about a classic computer science challenge: could you write a functional chess engine purely inside an analytical database using standard relational algebra?

The answer is yes. In fact, you can express the entire engine—generating moves, validating legality, scoring positions, and bubbling up the best strategy—inside a single WITH RECURSIVE query.

One grand recursive CTE

Recursive CTEs can handle a minimax tree search, just like the recursive minimax algorithm is implemented with imperative languages. By combining a top-down expansion of the board states with a bottom-up aggregation pass, DuckDB can execute a full minimax-based move search natively:

-- Expansion CTE: Top-down