playing sudoku in sql again with duckdb: sql Classic, BitMask, Bitmask + MRV · Issue #2136 · winpython/winpython
Repository navigation
playing sudoku in sql again with duckdb: sql Classic, BitMask, Bitmask + MRV #2136
New issue
New issue
Backlog
Feature
Backlog
playing sudoku in sql again with duckdb: sql Classic, BitMask, Bitmask + MRV #2136 Feature Labels
sql
Description
@stonebig's profile stonebig opened on Nov 29, 2026Asking again SQL to resolve a complex sudoku with duckdb.
all code was generated super-fast per google chrome AI... impressed
... the bottleneck is comprehension enough
In the demo shell of duckdb:
- version SqlDB >=2.0.0 syntax change: Replaced (val, i) -> ... with lambda val, i : ..., matching DuckDB 2.0's default lambda syntax (and also remaining backward-compatible with DuckDB 1.0-1.5).
- algorithm from Google IA (Gemini something?) "MRV + Bitmask Sudoku Solver (DuckDB 2.0+)"
- to apply on https://shell.duckdb.org/
- 3 version:
- classic original (from Oracle) version doing string comparison and searching stupdily from top left to bottom right cell
- bitmask: replacing string comparison par simple binary check ... about 20x faster
- bitmask +MRV : replacing "first empty cell" search per the "dancing link" search= the cell with the least possible options ... so SQL working like a python program
... about 1 second, for a complex sudoku, when it was 18 in standard sql and simple one
like for RH hypothesis, raw result without explanation is beurk:
pure classic sql
How It Works
· Board State. The puzzle is stored as an 81-character string where strpos(board, '0') finds the 1-based index of the next empty cell.
· Integer Division (//). DuckDB's // operator performs floor integer division, making it clean to calculate row, column, and 3×3 box offsets without explicit CAST or FLOOR calls.
· Pruning. The NOT EXISTS subquery filters out invalid digits at every step, pruning dead-end branches immediately so only valid paths continue to the next recursion depth.
WITH RECURSIVE
-- 1. Input puzzle (81 characters, '0' or '.' for empty cells)
input(board) AS (
SELECT '530070000600195000098000060800060003400803001700020006060000280000419005000080079'
),
-- 2. Digits 1 through 9
digits(d) AS (
SELECT range::VARCHAR FROM range(1, 10)
),
-- 3. Recursive backtracking solver
solve(board, idx) AS (
SELECT board, strpos(board, '0')
FROM input
UNION ALL
SELECT
substr(s.board, 1, s.idx - 1) || d.d || substr(s.board, s.idx + 1),
strpos(substr(s.board, 1, s.idx - 1) || d.d || substr(s.board, s.idx + 1), '0')
FROM solve s
CROSS JOIN digits d
WHERE s.idx > 0
AND NOT EXISTS (
SELECT 1
FROM range(0, 9) AS r(k)
WHERE
-- Check same row
substr(s.board, ((s.idx - 1) // 9) * 9 + k + 1, 1) = d.d
-- Check same column
OR substr(s.board, ((s.idx - 1) % 9) + k * 9 + 1, 1) = d.d
-- Check same 3x3 box
OR substr(
s.board,
(((s.idx - 1) // 27) * 27) + (((s.idx - 1) % 9) // 3) * 3 + (k // 3) * 9 + (k % 3) + 1,
1
) = d.d
)
)
-- 4. Format the solved 81-char string into a 9x9 grid
SELECT
regexp_replace(substr(board, r * 9 + 1, 9), '(.{3})', '\1 ', 'g') AS solved_grid
FROM solve, range(0, 9) AS rows(r)
WHERE idx = 0;
DuckDB 2.0+ Compatible Bitmask Sudoku Solver
One Caveat to Keep in Mind
While the logic is 100% valid SQL for DuckDB, harder puzzles can hit memory or performance limits with naive string-slicing backtracking because it explores many branches in breadth-first order.
If you want to solve "AI Escargot" or 17-clue puzzles without blowing up memory, DuckDB supports Minimum Remaining Values (MRV) ordering or bitmasking (BIT_OR), which drastically cuts down the search space.
Why This Is Much Faster
· O(1) Conflict Checks: Combining rows[r] | cols[c] | boxes[b] gives a single 9-bit mask of all forbidden digits for the current cell. Checking & b.mask = 0 replaces 27 string extractions per candidate.
· Native List Lambdas: DuckDB's list_transform updates the 9-element state arrays in place during the recursive step without string parsing.
The bitmask version is typically 5× to 15× faster per recursive step than a non-bit array/string version, depending on puzzle difficulty and how many candidate states get generated.
The speedup comes from replacing per-candidate array scans with constant-time bitwise operations, though both versions still share the same search-tree size (number of explored states) because they fill empty cells in the exact same left-to-right order.
WITH RECURSIVE
-- 1. Hard puzzle ("AI Escargot")
input(board) AS (
SELECT '100007090030020008009600500005300900010080002600004000300000010040000007007000300'
),
-- 2. Precompute bitmasks for digits 1..9
bits(d, mask) AS (
SELECT range::VARCHAR, 1 << (range - 1)
FROM range(1, 10)
),
-- 3. Unpack cells to compute initial bitmasks cleanly
cells AS (
SELECT
i AS idx,
i // 9 AS r,
i % 9 AS c,
(i // 27) * 3 + ((i % 9) // 3) AS b,
CASE
WHEN substr(board, i + 1, 1) != '0'
THEN 1 << (substr(board, i + 1, 1)::INT - 1)
ELSE 0
END AS mask
FROM input, range(0, 81) AS _(i)
),
row_masks AS (
SELECT list(m ORDER BY r) AS rows
FROM (SELECT r, bit_or(mask) AS m FROM cells GROUP BY r)
),
col_masks AS (
SELECT list(m ORDER BY c) AS cols
FROM (SELECT c, bit_or(mask) AS m FROM cells GROUP BY c)
),
box_masks AS (
SELECT list(m ORDER BY b) AS boxes
FROM (SELECT b, bit_or(mask) AS m FROM cells GROUP BY b)
),
-- 4. Recursive solver using O(1) bitwise checks and DuckDB 2.0 lambda syntax
solve(board, idx, rows, cols, boxes) AS (
SELECT
board,
strpos(board, '0') - 1,
rows,
cols,
boxes
FROM input, row_masks, col_masks, box_masks
UNION ALL
SELECT
substr(s.board, 1, s.idx) || b.d || substr(s.board, s.idx + 2),
strpos(substr(s.board, 1, s.idx) || b.d || substr(s.board, s.idx + 2), '0') - 1,
list_transform(s.rows, lambda val, i : CASE WHEN i = (s.idx // 9) + 1 THEN val | b.mask ELSE val END),
list_transform(s.cols, lambda val, i : CASE WHEN i = (s.idx % 9) + 1 THEN val | b.mask ELSE val END),
list_transform(s.boxes, lambda val, i : CASE WHEN i = ((s.idx // 27) * 3 + ((s.idx % 9) // 3)) + 1 THEN val | b.mask ELSE val END)
FROM solve s
CROSS JOIN bits b
WHERE s.idx >= 0
AND ((
s.rows[(s.idx // 9) + 1] |
s.cols[(s.idx % 9) + 1] |
s.boxes[((s.idx // 27) * 3 + ((s.idx % 9) // 3)) + 1]
) & b.mask) = 0
)
-- 5. Format the solved grid
SELECT
regexp_replace(substr(board, r * 9 + 1, 9), '(.{3})', '\1 ', 'g') AS solved_grid
FROM solve, range(0, 9) AS _(r)
WHERE idx = -1;
MRV + Bitmask Sudoku Solver (DuckDB 2.0+)
... MRV implements the classic (and human) strategy ("dansing links" ?) of exploring for the most obvious/constraint cell at every stage
... so we remove entirely the SQL "stupid algorithm" penalty
Where the Real 100× Speedup Comes From
Bitmasks make checking each state 5×-15× faster, but the biggest bottleneck in SQL Sudoku solvers is how many states are explored.
Adding Minimum Remaining Values (MRV) -- picking the empty cell with the fewest legal digits instead of the first '0' (strpos) -- shrinks the search tree on "AI Escargot" from tens of thousands of states down to a few hundred. With bitmasks, MRV is easy to compute using bit_count(511 & ~(row | col | box))
Instead of blindly picking the first '0' (strpos), it scores every empty cell by counting its remaining legal candidates (bit_count((511 & ~(row | col | box))::UTINYINT)) and branches on the most constrained cell first (often cells with only 1 forced move). That collapses the search tree on "AI Escargot" from tens of thousands of states down to ~200.
How to Measure the Exact Speedup Yourself
In the DuckDB Web Shell, run .timer on (or prepend EXPLAIN ANALYZE to either query) to compare:
- Total execution time (in milliseconds).
- Actual rows emitted by the Recursive CTE -- you'll see the state count drop from ~45,000 rows (left-to-right bitmask) down to ~200 rows (MRV + bitmask).
WITH RECURSIVE
-- 1. Hard puzzle ("AI Escargot")
input(board) AS (
SELECT '000000001000000023004005000000100000000030600007000580000067000010004000520000000'
),
-- 2. Precompute bitmasks for digits 1..9
bits(d, mask) AS (
SELECT range::VARCHAR, 1 << (range - 1)
FROM range(1, 10)
),
-- 3. Unpack cells to compute initial bitmasks
cells AS (
SELECT
i AS idx,
i // 9 AS r,
i % 9 AS c,
(i // 27) * 3 + ((i % 9) // 3) AS b,
CASE
WHEN substr(board, i + 1, 1) != '0'
THEN 1 << (substr(board, i + 1, 1)::INT - 1)
ELSE 0
END AS mask
FROM input, range(0, 81) AS _(i)
),
row_masks AS (
SELECT list(m ORDER BY r) AS rows FROM (SELECT r, bit_or(mask) AS m FROM cells GROUP BY r)
),
col_masks AS (
SELECT list(m ORDER BY c) AS cols FROM (SELECT c, bit_or(mask) AS m FROM cells GROUP BY c)
),
box_masks AS (
SELECT list(m ORDER BY b) AS boxes FROM (SELECT b, bit_or(mask) AS m FROM cells GROUP BY b)
),
-- 4. Recursive solver picking the most constrained empty cell (MRV) at each step
solve(board, rows, cols, boxes, next_idx) AS (
SELECT
board,
rows,
cols,
boxes,
(
SELECT arg_min(i, bit_count((511 & ~(rows[(i // 9) + 1] | cols[(i % 9) + 1] | boxes[((i // 27) * 3 + ((i % 9) // 3)) + 1]))::USMALLINT))
FROM range(0, 81) AS _(i)
WHERE substr(board, i + 1, 1) = '0'
)
FROM input, row_masks, col_masks, box_masks
UNION ALL
SELECT
next_state.board,
next_state.rows,
next_state.cols,
next_state.boxes,
(
SELECT arg_min(i, bit_count((511 & ~(next_state.rows[(i // 9) + 1] | next_state.cols[(i % 9) + 1] | next_state.boxes[((i // 27) * 3 + ((i % 9) // 3)) + 1]))::USMALLINT))
FROM range(0, 81) AS _(i)
WHERE substr(next_state.board, i + 1, 1) = '0'
)
FROM solve s
CROSS JOIN bits b
CROSS JOIN LATERAL (
SELECT
substr(s.board, 1, s.next_idx) || b.d || substr(s.board, s.next_idx + 2) AS board,
list_transform(s.rows, lambda val, i : CASE WHEN i = (s.next_idx // 9) + 1 THEN val | b.mask ELSE val END) AS rows,
list_transform(s.cols, lambda val, i : CASE WHEN i = (s.next_idx % 9) + 1 THEN val | b.mask ELSE val END) AS cols,
list_transform(s.boxes, lambda val, i : CASE WHEN i = ((s.next_idx // 27) * 3 + ((s.next_idx % 9) // 3)) + 1 THEN val | b.mask ELSE val END) AS boxes
) AS next_state
WHERE s.next_idx IS NOT NULL
AND ((
s.rows[(s.next_idx // 9) + 1] |
s.cols[(s.next_idx % 9) + 1] |
s.boxes[((s.next_idx // 27) * 3 + ((s.next_idx % 9) // 3)) + 1]
) & b.mask) = 0
)
-- 5. Format the solved grid (next_idx IS NULL means 0 empty cells remain)
SELECT
regexp_replace(substr(board, r * 9 + 1, 9), '(.{3})', '\1 ', 'g') AS solved_grid
FROM solve, range(0, 9) AS _(r)
WHERE next_idx IS NULL;
Metadata
Metadata
Assignees
No one assignedLabels
sql