I have a table and I need to retrieve the ID of the Second row. How to achieve that ?
By Top 2
I select the two first rows, but I need only
In SQL Server 2012+, you can use OFFSET...FETCH:
SELECT
<column(s)>
FROM
<table(s)>
ORDER BY
<sort column(s)>
OFFSET 1 ROWS -- Skip this number of rows
FETCH NEXT 1 ROWS ONLY; -- Return this number of rows
No need of row number functions if field ID is unique.
SELECT TOP 1 *
FROM (
SELECT TOP 2 *
FROM yourTable
ORDER BY ID
) z
ORDER BY ID DESC
select *
from (
select ROW_NUMBER() OVER (ORDER BY Column_Name) as ROWNO, *
from Table_Name
) Table_Name
where ROWNO = 2
SELECT TOP 2 [Id] FROM table
Use TOP 2
in the SELECT to get the desired number of rows in output.
This would return in the sequence the data was created. If you have a date option you could order by the date along with TOP n
Clause.
To get the top 2 rows;
SELECT TOP 2 [Id] FROM table
To get the top 2 rows order by some field
SELECT TOP 2 [ID] FROM table ORDER BY <YourColumn> ASC/DESC
To Get only 2nd Row;
WITH Resulttable AS
(
SELECT TOP 2
*, ROW_NUMBER() OVER(ORDER BY YourColumn) AS RowNumber
FROM @Table
)
SELECT *
FROM Resultstable
WHERE RowNumber = 2
I have a much easier way than the above ones.
DECLARE @FirstId int, @SecondId int
SELECT TOP 1 @FirstId = TableId from MyDataTable ORDER BY TableId
SELECT TOP 1 @SecondId = TableId from MyDataTable WHERE TableId <> @FirstId ORDER BY TableId
SELECT @SecondId