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
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.
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.
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.
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 .
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
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With