Generating Fractals with SQL Queries

I recently gave a talk at !!Con West about how you can use some of the dark corners of SQL to generate fractals. You can watch the recording here:



To summarize the video, I write SQL queries that generate two distinct classes of fractals:

  • Escape-time fractals – A class of fractals based on repeatedly evaluating a formula at every point in a grid.
  • Self-similar fractals – A class of fractals that can be described by what’s known as an “L-system“. An L-system encodes a fractal as an initial string and rules for modifying that string. It is then possible to decode the fractal from the string.

The primary SQL technique I use are recursive CTEs. I use recursive CTEs as a way to express iteration in my queries. With some work, I map both of the classes of fractals into SQL queries.

For escape-time fractals, I use one recursive CTE to iterate through every point in a grid. I then use a second recursive CTE to repeatedly evaluate a function over each point to test whether or not the point is part of the fractal.

For self-similar fractals, I wrote a SQL query that takes an arbitrary L-system. It runs a few iterations of the L-system and then maps the resulting string back to the fractal. Mapping the L-system to the final fractal is a bit tedious, but not too hard.

You can find all the queries I used in the talk here. Feel free to try them out yourself!


By the way, if you are working on scaling Postgres, I'm currently working on Perfalytics. Perfalytics is a service designed to help teams scale out Postgres by giving them insight into why their queries are slow and how they can go about making their queries faster. If you're interested in learning more about Perfalytics shoot me an email at michaelmalis2@gmail.com.

Leave a Reply

Your email address will not be published. Required fields are marked *