My Head in Lego: Mind The Gap

How SQL Server directed a 40-second Lego video without drawing a frame, and what 8,669 bricks cost if you build it for real.

My head in Lego: it builds, rewinds, grows a brain and a skull, gets its skin back and is then cut open Head, no brain, rewind, brain, skull, skin, cutaway. 1,193 frames, every one of them scheduled by SQL Server.

Play with the interactive version: scrub the video frame by frame, with the SQL beside it →


In I Built My Head Out of Lego. Inside SQL Server 2025. I took a 3D model of my own head, loaded it into SQL Server and had T-SQL turn it into bricks. Then I noticed I’d built myself without a brain, so I built one of those as well, and made a short video of the whole lot going together.

Two things came back from readers. They wanted to know how the video was made, because a database isn’t the obvious place to start an animation. And they wanted to know what the bricks would cost if you built it for real.

Well, obviously building my head, not yours, would be weird. Well, not weird; pretty cool, actually. Build away.

So this is the follow-up, and I’ve tried to make it easy. There’s a new video. This time the head gets a skull, which sits in the gap between the skin and the brain. Hence the title. Every step that made the video is below, with the code that does it. Every brick is priced at LEGO’s own Pick a Brick shop. And on the interactive page you can download the parts list, or the whole model as a file that BrickLink Studio opens.

None of it is special to my head. The database doesn’t know it’s a head. It gets a 3D model, fills it with bricks, colours them and counts them. Give it a different model and you get different bricks, and a parts list to go with them. Your own head, or anything else you like. The scripts are in the previous project. This article is just the explanation.

The answer to the second question is £1,009, by the way.

Nine stills from the video, one for each phase, each with its caption written as a line of SQL The nine phases. The captions are rows in a table too.

SQL Server doesn’t draw a single frame

SQL Server writes a script: a list of the bricks, each with up to four frame numbers saying when it arrives and when it leaves. That goes out once, as two CSV files. Blender has the lot before it draws frame 1, and from then on it asks every brick the same question: is this frame between your T1 and T2, or between your T3 and T4?

One PowerShell script, video_skull.ps1, runs five programs one after another: SQL Server, PowerShell itself, Blender, Python and ffmpeg. I’ll take them in that order.

Some numbers before we start. 8,669 bricks. 30,614 studs. 1,193 frames at 30 a second. About 1.1 seconds to render each frame on an RTX 5090.

1. SQL Server writes the script

The SQL Server stage: lego.Brick feeds lego.SkullVideoTimeline, which fills lego.VideoScript and lego.VideoPhase This is the only part that knows what happens when.

It starts with three finished models in lego.Brick, one row per brick: where it sits (X and Z in studs, Y in layers), how big it is, its part and its colour.

SELECT Model = m.Name, Bricks = COUNT(*), Studs = SUM(b.SizeX * b.SizeZ)
FROM lego.Brick AS b
JOIN lego.Model AS m ON m.ModelID = b.ModelID
WHERE m.ModelID IN (2, 4, 6)
GROUP BY m.Name;

Query result: the head has 4,149 bricks, the skull 2,347 and the brain 2,173

A stud is 8 mm and a layer is 9.6 mm, so the grid numbers are all Blender needs to place a brick. Every brick is one layer tall, which is why studs and voxels come to the same 30,614.

The director

lego.SkullVideoTimeline is the director. It puts the bricks in a queue with ROW_NUMBER() and turns each brick’s place in the queue into a frame number: start + n / rate. Integer division does the pacing, so 14 brain bricks share each frame.

Every brick also gets an angle round the head, so each layer is laid in a ring.

/* every brick gets an angle round the head, so each layer is laid in a ring */
Angle = ATN2(b.Z + b.SizeZ / 2.0 - @cz, b.X + b.SizeX / 2.0 - @cx + 1e-9),   -- ATN2(0, 0) is an error

/* C. The brain, up the spinal cord */
DECLARE @StartC int = @EndB + @Hold / 2;                                      -- 359
WITH C AS (SELECT T1, n = ROW_NUMBER() OVER (ORDER BY Y, Angle) - 1
           FROM #T WHERE ModelID = @BrainModelID)
UPDATE C SET T1 = @StartC + n / @BrainRate;                                   -- 359 + n / 14

There are six steps, A to F, one for each act of the video.

The six steps of the timeline: build, rewind, brain, skull, skin and cutaway, with the bricks each one sets, the order and the frames Six steps. That’s the whole plot.

The gaps between the steps are holds of 36 or 72 frames. Nothing in the script changes then, and the camera does the work.

The script

The result is lego.VideoScript: one row per brick with up to four frame numbers. T1 and T2 bound its first life on screen, T3 and T4 its second, and NULL means never.

-- a brick is on screen at frame @Frame when
WHERE (@Frame >= T1 AND @Frame = T3 AND @Frame < T4)

-- one real brick for each of the eight life stories
SELECT BrickID, T1, T2, T3, T4 FROM lego.VideoScript WHERE BrickID IN (…);

Eight sample rows from lego.VideoScript, one for each kind of brick, showing T1 to T4

Nine more rows in lego.VideoPhase hold the phases: a name, a frame range and a caption.

SELECT Seq, Phase, FromFrame, ToFrame, Caption FROM lego.VideoPhase ORDER BY Seq;

The nine rows of lego.VideoPhase with their frame ranges and captions Row 6. The robot eyes from the last article finally made it out of the drawer.

2. PowerShell hands it over

The PowerShell stage: video_skull.ps1 runs the SQL, exports two CSV files and starts Blender

video_skull.ps1 runs the SQL files, grows a fresh skull and brain, calls lego.SkullVideoTimeline, exports both tables with sqlcmd, then starts Blender with no window and hands it the two file names.

Invoke-Sql "SELECT b.ModelID, b.X, b.Y, b.Z, b.SizeX, b.SizeZ, c.Hex,
                   ISNULL(s.T1, -1), ISNULL(s.T2, -1), ISNULL(s.T3, -1), ISNULL(s.T4, -1)
            FROM lego.VideoScript AS s
            JOIN lego.Brick  AS b ON b.BrickID  = s.BrickID
            JOIN lego.Colour AS c ON c.ColourID = b.ColourID
            ORDER BY COALESCE(s.T1, s.T3);" -OutFile $script
Invoke-Sql "SELECT Seq, Phase, FromFrame, ToFrame, Caption FROM lego.VideoPhase ORDER BY Seq;" -OutFile $phases

& $Blender -b --factory-startup -noaudio --python tools\render_video.py -- $script $frames `
    --phases $phases --fstop 5.6 --view AgX --backdrop 3.5 --exposure 0.15 --res 1920x1080 --samples 64

script.csv has 8,669 lines and phases.csv has 9. That’s the only data that ever leaves SQL Server. NULL can’t travel in a CSV, so it goes as -1.

The first three lines of script.csv. The columns are ModelID, X, Y, Z, SizeX, SizeZ, Hex, T1, T2, T3, T4.

2,15,1,31,8,2,D7BA8C,1,-1,-1,-1
2,21,2,29,8,2,D7BA8C,1,-1,-1,-1
2,23,1,31,6,2,D7BA8C,1,-1,-1,-1

The first one is a Tan 2 × 8 on layer 1 of the neck. It arrives on frame 1 and never leaves.

3. Blender does what it’s told

The Blender stage: read the script into two point clouds, set a camera shot for each phase, then for every frame let Geometry Nodes pick the bricks and Cycles render them Two jobs done once, then two jobs done 1,193 times.

Points, not bricks

Python reads script.csv and builds two meshes that are only points: one per brick (8,669) and one per stud (30,614). Every point carries its brick’s t1, t2, t3, t4, size and colour as attributes. -1 becomes NEVER, which is ten million.

STUD, LAYER = 0.008, 0.0096            # metres
NEVER = 1.0e7

def world(x, layer, z):
    """Lego grid -> Blender metres: Z up, the face looking down -Y."""
    return ((x - cx) * STUD, -(z - cz) * STUD, (layer - y0) * LAYER)

for m, x, y, z, sx, sz, hx, t1, t2, t3, t4 in bricks:
    times = {"t1": t(t1), "t2": t(t2), "t3": t(t3), "t4": t(t4)}      # -1 -> NEVER
    brick_pts.append((world(x + sx / 2, y + 0.5, z + sz / 2),
                      dict(times, col=linear(hx), size=(sx * STUD - GAP, sz * STUD - GAP, LAYER - GAP))))
    for i in range(sx):
        for j in range(sz):                                          # a point for every stud
            stud_pts.append((world(x + i + 0.5, y + 1, z + j + 0.5), dict(times, col=linear(hx))))

The bricks never become 8,669 objects. They stay as points with numbers attached, and that’s what keeps Blender fast.

The camera reads the same table

phases.csv becomes a shot list. Each phase name has a camera position, and Blender keyframes it on that phase’s last frame and eases in between. So lego.VideoPhase directs the camera as well as the captions.

SHOTS = {               # yaw, elevation, distance (m), look-at height (fraction of the head)
    "start":   (-40, 30, 2.05, 0.45),
    "build":   (-15, 30, 2.05, 0.45),
    "empty":   (-10, 44, 1.80, 0.50),     # look down into the empty skull
    "rewind":  (0, 28, 2.05, 0.40),
    "brain":   (25, 22, 1.95, 0.48),
    "skull":   (8, 12, 1.75, 0.50),       # turn to face the skull
    "eyes":    (0, 8, 1.70, 0.54),        # push in on the eyes
    "skin":    (30, 22, 2.00, 0.45),
    "cutaway": (50, 26, 1.75, 0.55),      # the cut faces the camera
    "end":     (80, 22, 1.85, 0.50),
}
keys = [(1, SHOTS["start"])] + [(to, SHOTS[name]) for name, _, to in phases]
for frame, (yaw, elev, dist, look) in keys:
    pivot.rotation_euler = (math.radians(-elev), 0, math.radians(yaw))
    pivot.location = (0, 0, top * look)
    cam.location = (0, -dist, 0)
    pivot.keyframe_insert("rotation_euler", frame=frame)

A WHERE clause made of nodes

For every frame, the Scene Time node gives the frame number. Every point compares it with its own t1 to t4, and only the points that pass get a brick (or a stud) instanced on them. A new brick drops 3.5 cm over 6 frames and a leaving one lifts out the same way.

It’s the WHERE clause from lego.VideoScript, rebuilt out of nodes.

The Geometry Nodes tree: Scene Time and four Named Attribute nodes feed four Compare nodes, two Ands and an Or, which drive Instance on Points Four compares, two ANDs and an OR.

# (frame >= T1 and frame = T3 and frame < T4)
frame  = N.new("GeometryNodeInputSceneTime").outputs["Frame"]
second = compare("GREATER_EQUAL", frame, t3)
visible = boolean("OR",
                  boolean("AND", compare("GREATER_EQUAL", frame, t1), compare("LESS_THAN", frame, t2)),
                  boolean("AND", second, compare("LESS_THAN", frame, t4)))
Lk.new(visible, inst.inputs["Selection"])          # only visible points get a brick

# drop in: 1 -> 0 over 6 frames after appearing, lift out: 0 -> 1 over 6 frames before leaving
appear  = t1 + (t3 - t1) * second
drop_in = clamp((appear + DROP_FRAMES - frame) / DROP_FRAMES)
leave   = t2 + (t4 - t2) * second
lift    = clamp((frame - (leave - DROP_FRAMES)) / DROP_FRAMES)
translation.z = max(drop_in, lift) ** 2 * DROP     # DROP = 3.5 cm

Cycles renders the frame

Path tracing on the RTX 5090 with OptiX: 64 samples, denoised, 1920 × 1080, AgX colour, f/5.6 depth of field and a shadow-catcher floor. Then it writes a PNG and moves on. Frames already on disk are skipped, so a stopped render carries on where it left off.

scene.render.engine = "CYCLES"
scene.cycles.samples = 64
scene.cycles.device = "GPU"                     # OptiX on the RTX 5090
scene.cycles.denoiser = "OPTIX"
scene.view_settings.view_transform = "AgX"
cam.data.dof.focus_object = pivot               # f/5.6, focused on the head
floor.is_shadow_catcher = True
scene.render.filepath = os.path.join(a.out, "frame_")
scene.render.use_overwrite = False              # re-running carries on where it stopped
bpy.ops.render.render(animation=True)

1,193 frames at about 1.1 seconds each is roughly 22 minutes, and 2.3 GB of PNGs with no words on them yet.

4. Python puts the captions on

The Python stage: caption_frames.py draws each phase’s caption on the frames

caption_frames.py opens each PNG, finds the phase its frame number falls in, and draws that phase’s caption in a dark SSMS-style panel, with keywords in blue, strings in salmon and comments in green. Each caption fades in and out over 10 frames.

for start, end, caption in phases:
    if start <= n <= end:
        alpha = min(1.0, (n - start + 1) / FADE, (end - n + 1) / FADE)
        d.rounded_rectangle(box, radius=pad // 2, fill=(30, 30, 30, round(215 * alpha)))
        for kind, t in tokens(caption):                    # T-SQL syntax colours
            d.text((x, y), t, font=mono, fill=COLOURS[kind] + (round(255 * alpha),))
            x += mono.getlength(t)

5. ffmpeg makes the video

The ffmpeg stage: the numbered PNGs become trevor_skull.mp4

It reads the numbered PNGs at 30 a second and encodes them: 1920 × 1080, 39.8 seconds, 13 MB. This is the first time the frames are a video.

& ffmpeg -y -loglevel error -framerate 30 -i (Join-Path $captioned 'frame_%04d.png') `
    -c:v libx264 -pix_fmt yuv420p -crf 18 -preset slow -movflags +faststart $mp4

One brick, four numbers

Every row in lego.VideoScript has room for two lives on screen: T1 to T2, then T3 to T4. A NULL end means the brick stays to the end.

visible = (frame >= T1 AND frame < T2) OR (frame >= T3 AND frame < T4)

I expected this to get complicated, but eight patterns cover all 8,669 bricks. Each bar below is one real brick from its group, drawn against the nine phases.

Eight kinds of brick life: neck, face and sides, crown, skull and brain, some of them leaving again in the cutaway The face is the busy one. Built, rewound, built again, and some of it cut away.

Watch it with the SQL

The interactive page replays the video in your browser from the same script Blender read. Same rule for which bricks are showing, same 6-frame drop. You can drag the head round, step a frame at a time and click any brick to follow it.

Here it is on frame 470, part way through the brain.

The browser replay on frame 470: the brain half grown on its spinal cord, with the phase bar and the running cost underneath £576.53 spent so far. The meter runs as the bricks arrive.

Beside it, a panel keeps up with the frame: the step that scheduled whatever is moving, and the query for what’s on screen.

The SQL panel on frame 470: step C of the timeline, the 14 bricks that get T1 = 470, and the query for which bricks are visible

The second tab works one brick through the Geometry Nodes, with real numbers.

The Blender panel on frame 470: the bricks in the air this frame, and one brick’s visibility and drop worked through line by line

And frame 1,000, in the cutaway, where bricks are leaving and not arriving.

The browser replay on frame 1,000: the head with a corner cut away to show the skull and the eye

The SQL panel on frame 1,000: step F, the cutaway, and the 8 bricks that are gone from this frame on

Build it for real

This is the bit people asked about. I’ve priced every brick at LEGO’s Pick a Brick shop in the UK, using the prices on 23 November 2026. It’s one price per part. Where LEGO charges a range across colours (the 2 × 4 and 2 × 6), I’ve used the standard, higher price, because that’s what Tan and Medium Nougat cost.

The head costs £481.58, the skull £313.93 and the brain £213.96. All three come to £1,009.47 for 8,669 bricks, or 11.6p each

It’s eleven rows of prices and one join.

SELECT Model = ISNULL(m.Name, N'All three'), Bricks = COUNT(*),
       Studs = SUM(b.SizeX * b.SizeZ), CostGBP = SUM(pp.PriceGBP)
FROM lego.Brick AS b
JOIN lego.Model     AS m  ON m.ModelID = b.ModelID
JOIN lego.PartPrice AS pp ON pp.PartID = b.PartID
WHERE b.ModelID IN (2, 4, 6)
GROUP BY ROLLUP (m.Name);

Query result: cost by model, with a total of 8,669 bricks, 30,614 studs and £1,009.47

The shopping list itself is a table-valued function, with one row per part and colour, split by model.

SELECT TOP (5) * FROM lego.KitPartsList(2, 4, 6) ORDER BY TotalGBP DESC;

The five most expensive lines of the parts list. White 2 x 8 bricks for the skull come top at £53.90

Per brick, the skull is the dearest at 13.4p, against 11.6p for the head and 9.8p for the brain. It’s nearly all one colour, so the merge can use long bricks, including 154 white 2 × 8s at 35p each. The head’s colour changes chop it into cheap 1 × 1s and 1 × 2s.

Where the money goes

Each of the eleven brick sizes with its price, how many are needed, how many colours are used and the total. The 1 x 2 costs the most at £223.50 Three sizes make up more than half the bill.

“On Pick a Brick” is how many colours LEGO lists that part in. It doesn’t stock every size in every colour. The 2 × 8 comes in only 13, so a real order would fill some lines from BrickLink, usually for a little more.

Three ways to pay for 8,669 bricks

Pick a Brick with exact parts is £1,009. At LEGO set prices it would be about £790. At brick-tub prices, about £289

The set price comes from Brickset data for 14,752 sets from 1979 to 2019, in sets-brickset.csv from iechevarria/lego-price-analysis. The median takes UK-priced sets of 100 pieces or more.

Take the kit away

The interactive page has two buttons. One downloads the parts list as a CSV. The other downloads a kit: the model as an LDraw file, the parts list and a README. You can have the head on its own, or the head, skull and brain together.

LDraw is the open file format the LEGO CAD world runs on. It’s one line per brick (colour, position, rotation, part), with a 0 STEP after every layer so it reads as building instructions. BrickLink Studio, LeoCAD and LDView all open it, and Studio can turn it into a BrickLink wanted list.

Hope you enjoyed the article. If you do build a head, yours or anybody else’s, send me a picture.

Trevor (@sqlartist)

Responses

Comment with a free GitHub account, or use the form below to send Trevor a private note.

More from Trevor Dwyer