Does anyone know why sql server prefers to query the table twice? Is there any explanation? Can this be done with just one table?
This is a sample code:
DECLARE @id1stBuild INT = 1 ,@number1stBuild INT = 2 ,@idLastBuild INT = 5 ,@numberLastBuild INT = 1; DECLARE @nr TABLE (nr INT); INSERT @nr VALUES (1),(2),(3),(4),(5),(6),(7),(8),(9),(10); CREATE TABLE building ( id INT PRIMARY KEY identity(1, 1) ,number INT NOT NULL ,idStreet INT NOT NULL ,surface INT NOT NULL ) INSERT INTO building (number,idStreet,surface) SELECT bl.b ,n.nr ,abs(convert(BIGINT, convert(VARBINARY, NEWID()))) % 500 FROM ( SELECT ROW_NUMBER() OVER (ORDER BY n1.nr) b FROM @nr n1 CROSS JOIN @nr n2 CROSS JOIN @nr n3 ) bl CROSS JOIN @nr n
The execution plan for this is always the same: two clustered indexes are merged through a merge join (Concatenation). The rest is less important. Here is the execution plan:

source share