Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

T-SQL How to select only Second row from a table?

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 the second row

like image 940
Tony Avatar asked Sep 01 '10 10:09

Tony


People also ask

How do I find the second row in a table in SQL?

Method 1: The Older Method – Temp Table – 2nd Row. One of the most simple methods is to create a temporary table with the identity column and insert the result of this query inside that table and select the 2nd, 4th and 7th row based on the identity table.

How do I select a specific row in a table in SQL?

To select rows using selection symbols for character or graphic data, use the LIKE keyword in a WHERE clause, and the underscore and percent sign as selection symbols. You can create multiple row conditions, and use the AND, OR, or IN keywords to connect the conditions.

How will you select 2nd last row from a table?

Here is the query to get the second last row of a table in MySQL. mysql> select *from secondLastDemo order by StudentId DESC LIMIT 1,1; The output displays the second last record.

How do I select the second result in SQL?

A SQL result set returns rows in an indeterminate order, unless you have an order by . Even running the query twice on the same system and return the rows in different order, so you need the order by . The offsets start at 0 for the first row. For the second row, offset 1 .


3 Answers

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
like image 154
SQLDiver Avatar answered Oct 20 '22 06:10

SQLDiver


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
like image 34
Martin Smith Avatar answered Oct 20 '22 07:10

Martin Smith


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
like image 22
Mudassir Hasan Avatar answered Oct 20 '22 07:10

Mudassir Hasan