Does anyone know why sql server chooses to query the table 'building' twice? Is there any explanation? Can it be done with only one table seek?
This is the code sample:
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
--***** execution plan for the select below
SELECT *
FROM building b
WHERE b.id = @id1stBuild
AND b.number = @number1stBuild
OR b.id = @idLastBuild
AND b.number = @numberLastBuild
DROP TABLE building
The execution plan for this is always the same: Two Clustered Index Seek unified through Merge Join (Concatenation). The rest is less important. Here is the execution plan: