Generally, there are no better approaches, searching for a non-indexed column must perform linear search.
But in your case, if the primary key is auto increment and createddate
represents the record creation date (which means greater primary key, later createddate
date/time record), you may manually perform a binary search on the primary key.
Below is an example, with ID
is an auto increment primary key (indexed) starting from 0. Each selection statement involved ID
only so the query is fast.
Please note that this may work only if the createddate
is sorted relative to the primary key ID
:
DECLARE @lowerBoundID INT
DECLARE @upperBoundID INT
DECLARE @maxID INT
SELECT @maxID = MAX(ID) FROM productdetail
SET @lowerBoundID = 0
SET @upperBoundID = @maxID
IF (SELECT createddate FROM productdetail WHERE ID = @lowerBoundID) > '05 mar 2016' OR (SELECT createddate FROM productdetail WHERE ID = @upperBoundID) < '01 Jan 2016'
BEGIN
DECLARE @first INT
DECLARE @last INT
DECLARE @middle INT
SET @first = 0
SET @last = @maxID
SET @middle = (@first + @last) / 2
WHILE @last - @first > 1
BEGIN
IF (SELECT createddate FROM productdetail WHERE ID = @middle) < '01 Jan 2016'
SET @first = @middle
ELSE
SET @last = @middle
SET @middle = (@first + @last) / 2
END
IF (SELECT createddate FROM productdetail WHERE ID = @first) < '01 Jan 2016'
SET @lowerBoundID = @last
ELSE
SET @lowerBoundID = @first
SET @first = 0
SET @last = @maxID
SET @middle = (@first + @last) / 2
WHILE @last - @first > 1
BEGIN
IF (SELECT createddate FROM productdetail WHERE ID = @middle) > '05 mar 2016'
SET @last = @middle
ELSE
SET @first = @middle
SET @middle = (@first + @last) / 2
END
IF (SELECT createddate FROM productdetail WHERE ID = @last) > '05 mar 2016'
SET @upperBoundID = @first
ELSE
SET @upperBoundID = @last
SELECT * FROM productdetail WHERE ID >= @lowerBoundID AND ID <= @upperBoundID
END