Reputation: 149
I'm using SQL Server. I have an SQL Query which returns more than one row and I need to select only the 2nd result from it or the first result may be. What query should I write for this requirement?
Upvotes: 1
Views: 10020
Reputation: 1
SELECT t.*
FROM table_name t
OFFSET 1 ROW
LIMIT 1
If you want the second record in a sorted list, this will work.
The offset will bump it off one row (according to sort). The limit 1 will return only 1 row.
Upvotes: -2
Reputation: 2032
We can use TOP
clause for this -
SELECT TOP (1) Col1 FROM (Your SQL Query) as XYZ Order By Col3 DESC
Upvotes: 1
Reputation: 33
SELECT * FROM TABLE ORDER BY COLUMN ASC LIMIT 1 TO FETCH FIRST ROW
SELECT * FROM TABLE ORDER BY COLUMN DESC LIMIT 1 TO FETCH LAST ROW
Upvotes: 0
Reputation: 353
You can try
SELECT * FROM
(
SELECT r.*, ROW_NUMBER() OVER (ORDER BY SomeField ASC) AS RowNum
) sorty
WHERE RowNum = 2
Upvotes: 2
Reputation: 1269623
You can use offset
/fetch
:
select t.*
from t
order by col
offset 1 fetch next 1 row only;
Notes:
order by
. Even running the query twice on the same system and return the rows in different order, so you need the order by
.offset 1
.offset
/fetch
is ANSI standard syntax.Upvotes: 6