I enjoy seeing PostgreSQL used for playful and creative projects, from solving Advent of Code puzzles to exploring mathematical functions and rendering fractal art with SQL. These examples show SQL as more than a tool for routine data work, and the recursive query below builds on the kinds of SQL techniques and data generation I discuss in postgres sql techniques and generating data series.
I recommended @turnstep’s 2022 Advent of Code collection as “some fun reading”: he completed it all in Postgres, and the effort took him “most of a year.” The collection is on the Crunchy Data blog at https://t.co/8JzHuFJHDr.
I called @turnstep’s accomplishment “pretty 🤯” after he got through the 2022 collection all in Postgres.
My favorite function in Postgres is allballs.
I presented a recursive PostgreSQL query beginning with WITH RECURSIVE that generates a character-grid visualization through repeated calculations.
WITH RECURSIVE
x(i)
AS (
VALUES(0)
UNION ALL
SELECT i + 1 FROM x WHERE i < 101
),
Z(Ix, Iy, Cx, Cy, X, Y, I)
AS (
SELECT Ix, Iy, X::float, Y::float, X::float, Y::float, 0
FROM
(SELECT -2.2 + 0.031 * i, i FROM x) AS xgen(x,ix)
CROSS JOIN
(SELECT -1.5 + 0.031 * i, i FROM x) AS ygen(y,iy)
UNION ALL
SELECT Ix, Iy, Cx, Cy, X * X - Y * Y + Cx AS X, Y * X * 2 + Cy, I + 1
FROM Z
WHERE X * X + Y * Y < 16.0
AND I < 27
),
Zt (Ix, Iy, I) AS (
SELECT Ix, Iy, MAX(I) AS I
FROM Z
GROUP BY Iy, Ix
ORDER BY Iy, Ix
)
SELECT array_to_string(
array_agg(
SUBSTRING(
' .,,,-----++++%%%%@@@@#### ',
GREATEST(I,1),
1
)
),''
)
FROM Zt
GROUP BY Iy
ORDER BY Iy;
My recursive fractal query uses the condition X * X + Y * Y < 16.0 and an iteration limit of 27.