2

How can I get the n-th row of a TSQL query results?

Let's say, I want to get the 2nd row of this SELECT:

SELECT * FROM table
ORDER BY 2 ASC
pencilCake
  • 51,323
  • 85
  • 226
  • 363
  • What's the structure of your table (the columns)? And it's for SQL Server, Oracle, Sybase ASE, DB2 ? – aF. Dec 14 '11 at 14:24

3 Answers3

6

What version of SQL Server are you targeting? If 2005 or greater, you can use ROW_NUMBER to generate a row number and select using that number. http://msdn.microsoft.com/en-us/library/ms186734.aspx

WITH orderedtable AS
(
    SELECT *, ROW_NUMBER() OVER (ORDER BY <your order here>) AS 'RowNumber'
    FROM table
) 
SELECT * 
FROM orderedtable 
WHERE RowNumber = 2;
moribvndvs
  • 42,191
  • 11
  • 135
  • 149
1

You can use a trick combining TOP with ORDER BY ASC/DESC to achieve an effect similar to MySQL's LIMIT:

SELECT TOP 2 * INTO #temptable FROM table
ORDER BY 2 ASC

SELECT TOP 1 * FROM #temptable
ORDER BY 2 DESC

or without temptable, but nested statements:

SELECT TOP 1 * FROM
(
    SELECT TOP 2 * FROM table
    ORDER BY 2 ASC
) sub
ORDER BY 2 DESC

The first time you select all rows up to the one you want to actually have, and in the second query you select only the first of the remaining when ordering them reversely, which is exactly the one you want.

Source: http://www.planet-source-code.com/vb/scripts/ShowCode.asp?txtCodeId=850&lngWId=5

codeling
  • 11,056
  • 4
  • 42
  • 71
0

One way;

;with T(rownumber, col1, colN) as (
    select 
         row_number() over (order by ACOLUMN) as rownumber,
         col1,
         colN
    from 
         atable
)
select * from T where rownumber = 2
Alex K.
  • 171,639
  • 30
  • 264
  • 288