My Head in Lego: Mind The Gap

Lego · SQL Server 2025 · Blender

My Head in Lego: Mind The Gap

Last time I built my head out of Lego inside SQL Server and made a video of it. Two questions came back. How was the video made? And what would the bricks cost? This page answers both, and you can take the parts list away with you.

bricks in the script
8,669
studs
30,614
frame numbers per brick
T1–T4
files handed to Blender
2
frames at 30 fps
1,193
per frame, RTX 5090
≈1.1 s
in UK Pick a Brick bricks
£1,009

If you missed the last one

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, and each card opens to show the code that does it. Every brick is priced at LEGO's own Pick a Brick shop. 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 page is just the explanation.

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

How the video was made

One script, video_skull.ps1, runs five programs one after another. Each coloured band below is one of them, and the labels between the cards say what gets handed on. Open any card to see the code.

SQL Server doesn't draw a single frame. It 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?

SQL Server 2025the LegoSQL database
lego.Brickbuilt earlier by build.ps1, 07_Brain.sql, 09_Skull.sql Three finished models, one row per brick: where it sits (X and Z in studs, Y in layers), how big it is (SizeX × SizeZ), 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;
ModelBricksStuds
1Trevor head (2x life size)414914544
2Trevor skull (2x life size)234710412
3Trevor brain in skull (2x life size)21735658

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.

8,669 brick rows
lego.SkullVideoTimelinesql/10_SkullVideo.sql This 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. Six steps, A to F, one for each act.
/* 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
StepSetsWhich bricksORDER BYPer frameFrames
A · buildT1head, Y ≤ 53 (@Stop)Y, Angle181–205
B · rewindT2head, 12 < Y ≤ 53Y DESC, Angle DESC50277–341
C · brainT1brainY, Angle14359–514
D · skullT1skullY, Angle16532–678
E · skinT3head, Y > 12 (@Back)Y, Angle24750–902
F · cutawayT4 head, T2 skullInCut = 1head first, Y DESC8938–1043

The gaps between the steps are @Hold frames (36, or 72 when doubled). Nothing in the script changes then, and the camera does the work.

UPDATE … SET T1, T2, T3, T4 · INSERT 9 phases
lego.VideoScript + lego.VideoPhasethe script, in two tables 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. Nine more rows hold the phases: a name, a frame range and a caption.
-- a brick is on screen at frame @Frame when
WHERE (@Frame >= T1 AND @Frame < T2) OR (@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 (…);
loading…
SELECT Seq, Phase, FromFrame, ToFrame, Caption FROM lego.VideoPhase ORDER BY Seq;
script.csv · 8,669 lines   phases.csv · 9 linesThe only data that ever leaves SQL Server. NULL can't travel in a CSV, so it goes as -1.
PowerShellvideo_skull.ps1 with sqlcmd
video_skull.ps1the one script that runs everything 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

The first three lines of script.csv. Columns: 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

That's a Tan 2 × 8 on layer 1 of the neck: it arrives on frame 1 and never leaves.

blender -b --python render_video.py -- script.csv frames …Blender starts headless with the script file as an argument.
Blender 5.1headless, running tools/render_video.py
Read the script into two point cloudsrender_video.py, runs once 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, 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, which is what keeps Blender fast.

points with attributes t1 t2 t3 t4 size col
A camera shot for each phaserender_video.py, runs once 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)
scene.frame_end = 1193 · bpy.ops.render.render(animation=True)
for frame in 1 … 1,193:the player below is on frame 470
Geometry Nodes picks the bricksevery 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.
# (frame >= T1 and frame < T2) or (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
this frame's bricks and studs, some still in the air
Cycles renders the frameevery frame, about 1.1 s 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 frame_0470.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)
↻ next frame · 1,193 frames × ≈1.1 s ≈ 22 minutes
frame_0001.png … frame_1193.png · 2.3 GBThe frames have no words on them yet.
Python + PILtools/caption_frames.py
Captions from lego.VideoPhasetools/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)
captioned\frame_0001.png … frame_1193.png · 1.6 GB
ffmpegH.264 encoder
out/trevor_skull.mp41920 × 1080 · 39.8 s · 13 MB Reads the numbered PNGs at 30 a second and encodes them. 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
lego.Brick JOIN lego.PartPrice · back in the databaseThat's the video done. Now the money. The same 8,669 rows make a shopping list.
SQL Server 2025the shopping list, sql/11_PartPrice.sql

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.

Head£481.584,149 bricks
Skull£313.932,347 bricks
Brain£213.962,173 bricks
All three£1,009.478,669 bricks · 11.6p each
lego.PartPrice + lego.KitPartsListsql/11_PartPrice.sql Eleven rows of prices and one join. The shopping list is a table-valued function with one row per part and colour, split by model.
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);
ModelBricksStudsCostGBP
1Trevor brain in skull (2x life size)21735658213.96
2Trevor head (2x life size)414914544481.58
3Trevor skull (2x life size)234710412313.93
4All three8669306141009.47
SELECT TOP (5) * FROM lego.KitPartsList(2, 4, 6) ORDER BY TotalGBP DESC;
PartIDPartColourIDColourHeadSkullBrainQuantityPriceGBPTotalGBP
13007Brick 2 x 815White01540154.3553.90
23003Brick 2 x 215White34260429.1251.48
33004Brick 1 x 215White154300445.1044.50
43001Brick 2 x 415White01900190.1936.10
53004Brick 1 x 271Light Bluish Grey286680354.1035.40

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

PartEachBricksColours usedOn Pick a BrickTotal
3004Brick 1 × 2£0.102,2351643£223.50
3003Brick 2 × 2£0.121,4041339£168.48
3005Brick 1 × 1£0.062,7271542£163.62
3007Brick 2 × 8£0.35356813£124.60
3001Brick 2 × 4£0.195111237£97.09
3002Brick 2 × 3£0.165971220£95.52
3622Brick 1 × 3£0.123691432£44.28
2456Brick 2 × 6£0.28150928£42.00
3010Brick 1 × 4£0.132301240£29.90
3009Brick 1 × 6£0.2256730£12.32
3008Brick 1 × 8£0.2434718£8.16
125 part and colour lines8,669£1,009.47

"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, exact parts£1,00911.6p a brick. The only one where you get 2,727 1 × 1s in the colours you asked for.
At LEGO set prices≈ £790The median UK set in 2019 cost 9.1p a piece. But a set gives you its own pieces, not these ones.
At brick-tub prices≈ £289Classic 10717, Extra Large Brick Box: 1,500 pieces for £49.99 (3.3p each). Random colours, and plenty of pieces that aren't bricks.

Set prices: 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.

Export

The kit has the model as an LDraw file, the parts list as CSV and a README. LDraw is the open file format the LEGO CAD world runs on: 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. The CSV has the same columns as lego.KitPartsList, with LDraw part and colour numbers.

Watch it with the SQL

This is the video again, but running in your browser from the same script Blender read. Same rule for which bricks are showing, same 6-frame drop. Switch to Blender render for the real frames. Leave Show the SQL ticked and the panel keeps up with the frame: the step that scheduled whatever is moving, the query for what's on screen, and one brick worked through the Geometry Nodes.

Browser replay · drag to look round · click a brick
Loading 8,669 bricks…
Frame 470 / 1,193 · 15.6 sbrain
On screen now£0.000 bricks
Bought so far£0.000 of 8,669 bricks
of £1,009.47 at UK Pick a Brick prices. Rewound bricks go back on, so they're only bought once.

The browser replay draws plain boxes and studs with WebGL and uses Blender's camera keyframes, eased the same way. It shows what Geometry Nodes hands to Cycles before any path tracing happens. The Blender render view is the finished video, scaled to 720p, with the captions caption_frames.py drew.

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. 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. Click a row to find that brick in the replay.

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

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

Trevor (@sqlartist)