How to get second last data from MS Sql Server



To retrieve the second-to-last row from a table in Microsoft SQL Server, you can use the `OFFSET` and `FETCH` clauses along with the `ORDER BY` clause. Here's an example query:

SQL







SELECT *

FROM YourTableName

ORDER BY YourOrderByColumn DESC

OFFSET 1 ROW

FETCH NEXT 1 ROW ONLY;

In this query:

  • `YourTableName` is the name of your table.
  • `YourOrderByColumn` is the column by which you want to order the result set.
  • `ORDER BY YourOrderByColumn DESC` orders the result set in descending order based on the specified column.
  • `OFFSET 1 ROW` skips the first row.
  • `FETCH NEXT 1 ROW ONLY` retrieves only one row.

Make sure to replace `YourTableName` and `YourOrderByColumn` with the actual names from your database schema.

Note: This method assumes that there are at least two rows in your table. If there's a possibility that there might be only one row, you should handle that scenario accordingly.

Comments