T-SQL how to select previous row using indexes

WazHu 1 Reputation point
2021-12-21T05:12:52.483+00:00

Hi,

I've been trying to get the prev/next rows based on a current row using the primary key. That is I only want two rows, the previous to the current and the next. I have a huge DB table with 2 million rows and it takes like 30 seconds for the below query to run. It looks like it needs to run a query through the entire database to get the lag value etc. I have an index with all the columns in it for the order so how do I get SQL Server basically to find the current row using my primary key, use those values in the index values and find the previous and next rows (without having to go through an entire database/query). In theory SQL Server should know this right, it has the columns already sorted in order so it should be able to find that position in the index and give me the next/prev. Here is my query: (AddressID is the primary key) but I want the next/previous street, street number etc (that is the next physical address)

declare @previousID int; 
declare @nextID int; 

 select @previousID =  isnull(x.PreviousAddressID, 0) 
   , @nextID = isnull(x.NextAddressID, 0) 
 from 
 ( 
 select a.AddressID 
   , lag(a.AddressID) over (order by ElectorateID 
  , StreetID 
  , iStreetNumber 
  , StreetNumber 
  , iFlatNumber 
  , FlatNumber 
   ) PreviousAddressID 
   , lead(a.AddressID) over (order by ElectorateID 
   , StreetID 
   , iStreetNumber 
   , StreetNumber 
   , iFlatNumber 
   , FlatNumber 
    ) NextAddressID 
 from dbo.[Address] a 
 where ( 
   a.[ElectorateID] = @ElectorateID 
   and a.[Old] = @Old 
   ) 
 ) x 
 where x.AddressID = @AddressID 
Developer technologies Transact-SQL
{count} votes

1 answer

Sort by: Most helpful
  1. Erland Sommarskog 121.4K Reputation points MVP Volunteer Moderator
    2021-12-21T23:04:42.683+00:00

    Adding an index on (Old, ElectorateID, StreetID, iStreetNumber, StreetNumber, iFlatNumber, FlatNumber) INCLUDE (AddressId) could help.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.