T-SQL How to select only Second row from a table?
Solution 1:
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
Solution 2:
Assuming SQL Server 2005+ an example of how to get just the second row (which I think you may be asking - and is the reason why top
won't work for you?)
set statistics io on
;with cte as
(
select *
, ROW_NUMBER() over (order by number) as rn
from master.dbo.spt_values
)
select *
from cte
where rn = 2
/* Just to add in what I was running RE: Comments */
;with cte as
(
select top 2 *
, ROW_NUMBER() over (order by number) as rn
from master.dbo.spt_values
)
select *
from cte
where rn = 2
Solution 3:
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