Consider this table:DECLARE @ExampleTable TABLE ( ExampleColumn INTEGER PRIMARY KEY);INSERT INTO @ExampleTable VALUES (1)INSERT INTO @ExampleTable VALUES (3)INSERT INTO @ExampleTable VALUES (7)INSERT INTO @ExampleTable VALUES (14)INSERT INTO @ExampleTable VALUES (19)INSERT INTO @ExampleTable VALUES (26)INSERT INTO @ExampleTable VALUES (34)INSERT INTO @ExampleTable VALUES (40)INSERT INTO @ExampleTable VALUES (46)INSERT INTO @ExampleTable VALUES (50)
I want to select all the values from the table between 17 and 33 as well as the first value less than 17 and the first value greater than 33.Consider this query:SELECT * FROM @ExampleTable WHERE ExampleColumn BETWEEN ( SELECT MAX(ExampleColumn) FROM @ExampleTable WHERE ExampleColumn < 17) AND ( SELECT MIN(ExampleColumn) FROM @ExampleTable WHERE ExampleColumn > 33)
This query returns the results I am looking for, but unfortunately requires three clustered seeks.It occurs to be that there's really no reason that the database engine couldn't do this in one pass of the table.Can this query be rewritten to only need one clustered seek (for SQL Server 2012)?