This is similar to my blog-post: How to fetch second row from a table in SQL Server
To fetch rows from last, first you have to query number of rows in your table then use this number in OFFSET FETCH clause
Consider I have a table with following Data
Below is the query to fetch Last row in a result set
I am taking one more example, suppose I want last three rows
Below is the query
One more trick to get last row from a table using OFFSET FETCH Clause
Use reverse order DESC in place of ASC
Below is the query
To fetch rows from last, first you have to query number of rows in your table then use this number in OFFSET FETCH clause
Consider I have a table with following Data
SELECT [ID] ,[Name] ,[Post] FROM [JPDB].[dbo].[Employee]Result:
Below is the query to fetch Last row in a result set
DECLARE @Total [int] SET @Total= (SELECT COUNT(*) FROM [JPDB].[dbo].[Employee]) SELECT [ID] ,[Name] ,[Post] FROM [JPDB].[dbo].[Employee] ORDER BY [ID] ASC OFFSET (@Total-1) ROWS FETCH NEXT 1 ROWS ONLYResult:
I am taking one more example, suppose I want last three rows
Below is the query
DECLARE @Total [int] SET @Total= (SELECT COUNT(*) FROM [JPDB].[dbo].[Employee]) SELECT [ID] ,[Name] ,[Post] FROM [JPDB].[dbo].[Employee] ORDER BY [ID] ASC OFFSET (@Total-3) ROWS FETCH NEXT 3 ROWS ONLYResult:
One more trick to get last row from a table using OFFSET FETCH Clause
Use reverse order DESC in place of ASC
Below is the query
SELECT [ID] ,[Name] ,[Post] FROM [JPDB].[dbo].[Employee] ORDER BY [ID] DESC OFFSET 0 ROWS FETCH NEXT 1 ROWS ONLYResult
No comments:
Post a Comment