vikrant69g blog

Someone built a ray tracer in SQL and it actually works

ClickHouse's query language is Turing-complete. Someone proved it by rendering 3D scenes with recursive CTEs and array functions.

Abstract geometric rays refracting through translucent database table columns

The ClickHouse ray tracer is not a library that connects to ClickHouse. It is 700 lines of SQL that compute ray intersections, reflections, and shadows using common table expressions. The setup is straightforward. Define scene geometry as arrays of sphere coordinates. Write a recursive CTE that traces each ray from the camera through pixels, bouncing off surfaces until it hits a light source or the recursion limit. ClickHouse executes the query and outputs RGB values per pixel. This works because ClickHouse SQL has array operations, tuple destructuring, and recursive queries. You can write arrayMap to transform rays in parallel. You can use multiIf to handle surface normals and reflection angles. The result is a functioning Whitted-style ray tracer with zero external code. Performance is predictably terrible. Rendering a 640x480 frame takes minutes on modern hardware. But that misses the point. The exercise demonstrates that SQL dialects with enough primitives become general-purpose languages by accident. I have written detection queries in Snowflake that felt closer to Python than to traditional SQL. Window functions, lateral joins, and JSON unnesting turn relational algebra into something more expressive. ClickHouse takes that further with arrays and recursion. The practical takeaway is that your OLAP database might already have the primitives you need for batch computation. Before you export data to run a model or simulation, check if the query engine can do it inline. It will be slower than compiled code, but faster than moving gigabytes over the network. The impractical takeaway is that someone will eventually train a neural network in SQL. Probably also in ClickHouse.


Source: Rendering ray tracing in a database (ClickHouse)