Select next and previous id of record in sql with where condition

Select next and previous id of record in sql with where condition

If you have a table named with Student and having records, and you want all records with next and previous PKId or id with each records and you can use lag and lead functions.

SELECT 
Student.PKId
Student.Name,
Student.Address,
NextPrev.PreviousId,  
NextPrev.NextId  
FROM Student
                   OUTER APPLY  
                   (select PreviousId,NextId  
                    from (  
                        select   
                               lag(PKId) OVER (ORDER BY Student.PKId DESC) as PreviousId,  
                               PKId,  
                               lead(PKId) OVER (ORDER BY Student.PKId DESC) as NextId  
                        from Student WHERE Status=1 --Here Condition should be matched with main condition
                    ) as t  
                    WHERE PKId=@PKId) AS NextPrev  
                                           WHERE Student.Status=1 AND Student.Name='Veer' --you can remove this condition if you want all records


--or simply with all records 

SELECT 
Student.PKId
Student.Name,
Student.Address,
NextPrev.PreviousId,  
NextPrev.NextId  
FROM Student
                   OUTER APPLY  
                   (select PreviousId,NextId  
                    from (  
                        select   
                               lag(PKId) OVER (ORDER BY Student.PKId DESC) as PreviousId,  
                               PKId,  
                               lead(PKId) OVER (ORDER BY Student.PKId DESC) as NextId  
                        from Student
                    ) as t  
                    WHERE PKId=@PKId) AS NextPrev