# SQL Puzzle – Eight Queens on a Chess board

This puzzle was first proposed in 1848 by a composer of chess puzzles called Max Bezzel and has since spawned much analysis and many variants. Simply phrased, it goes as follows:

“Can you place 8 queen’s on a standard (8×8) chessboard so that no two queen’s threaten each other?”

(Just in case, I’ll remind you a queen can move and attack any number of squares in a straight line –  horizontally, vertically, or diagonally)

Here’s one example solution:

By all means have some fun trying to find extra solutions to this with pencil and paper or chessboard, however we do have computers (and SQL!) these days, so the real challenge is to try find ALL the possible solutions to this puzzle using T-SQL.

Enjoy 🙂

## 2 thoughts on “SQL Puzzle – Eight Queens on a Chess board”

1. luk says:

Easy ! I love SQL =)

with desk as
(
select col, row from
(select generate_series(1,8) as col) t1
cross join
(select generate_series(1,8) as row) t2
)
select *
from desk d1
join desk d2
on d1.row d2.row
and abs(d1.row – d2.row) 1
join desk d3
on d1.row d3.row
and abs(d1.row – d3.row) 2
and d2.row d3.row
and abs(d2.row – d3.row) 1
join desk d4
on d1.row d4.row
and abs(d1.row – d4.row) 3
and d2.row d4.row
and abs(d2.row – d4.row) 2
and d3.row d4.row
and abs(d3.row – d4.row) 1
join desk d5
on d1.row d5.row
and abs(d1.row – d5.row) 4
and d2.row d5.row
and abs(d2.row – d5.row) 3
and d3.row d5.row
and abs(d3.row – d5.row) 2
and d4.row d5.row
and abs(d4.row – d5.row) 1
join desk d6
on d1.row d6.row
and abs(d1.row – d6.row) 5
and d2.row d6.row
and abs(d2.row – d6.row) 4
and d3.row d6.row
and abs(d3.row – d6.row) 3
and d4.row d6.row
and abs(d4.row – d6.row) 2
and d5.row d6.row
and abs(d5.row – d6.row) 1
join desk d7
on d1.row d7.row
and abs(d1.row – d7.row) 6
and d2.row d7.row
and abs(d2.row – d7.row) 5
and d3.row d7.row
and abs(d3.row – d7.row) 4
and d4.row d7.row
and abs(d4.row – d7.row) 3
and d5.row d7.row
and abs(d5.row – d7.row) 2
and d6.row d7.row
and abs(d6.row – d7.row) 1
join desk d8
on d1.row d8.row
and abs(d1.row – d8.row) 7
and d2.row d8.row
and abs(d2.row – d8.row) 6
and d3.row d8.row
and abs(d3.row – d8.row) 5
and d4.row d8.row
and abs(d4.row – d8.row) 4
and d5.row d8.row
and abs(d5.row – d8.row) 3
and d6.row d8.row
and abs(d6.row – d8.row) 2
and d7.row d8.row
and abs(d7.row – d8.row) 1
where d1.col = 1
and d2.col = 2
and d3.col = 3
and d4.col = 4
and d5.col = 5
and d6.col = 6
and d7.col = 7
and d8.col = 8

Like

2. Chris Morse says:

generate_series(1,8) ??? Is the code for that available?

I had a valid solution to this in another language (Magic Software) back in 1997 … hated to lose it.

Like