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

Viewed 187093

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

17 Answers

you can use OFFSET and FETCH NEXT

SELECT id
FROM tablename
ORDER BY column
OFFSET 1 ROWS
FETCH NEXT 1 ROWS ONLY;

NOTE:

OFFSET can only be used with ORDER BY clause. It cannot be used on its own.

OFFSET value must be greater than or equal to zero. It cannot be negative, else return error.

The OFFSET argument is used to identify the starting point to return rows from a result set. Basically, it exclude the first set of records.

The FETCH argument is used to return a set of number of rows. FETCH can’t be used itself, it is used in conjuction with OFFSET.

I have a much easier way than the above ones.

DECLARE @FirstId int, @SecondId int

    SELECT TOP 1 @FirstId = TableId from MyDataTable ORDER BY TableId 
    SELECT TOP 1 @SecondId = TableId from MyDataTable WHERE TableId <> @FirstId  ORDER BY TableId 

SELECT @SecondId 

There is a relative simple solution based on comments from SQLDiver and Taha Ali.

Imagine there is a string containing 'domain\username' retrieved by function ORIGINAL_LOGIN() and i don't need the domain component.

First approach

DECLARE @Login NVARCHAR(100)
SELECT @Login = 'domain\username'
-- SELECT @Login = ORIGINAL_LOGIN()

SELECT
    VALUE
FROM
    STRING_SPLIT(@Login, '\')

returns a table having 2 rows. First row holds the domain and second row holds the requested username.

Using

DECLARE @Login NVARCHAR(100)
SELECT @Login = 'domain\username'
-- SELECT @Login = ORIGINAL_LOGIN()

SELECT
    VALUE
FROM
    STRING_SPLIT(@Login, '\')
ORDER BY
    (SELECT NULL)
OFFSET 1 ROWS
FETCH NEXT 1 ROWS ONLY;

returns exactly the second row from the temporary table.

Another idea is this:

 SELECT MIN(id) FROM
     (
      SELECT TOP 2(TAB.[id])
          FROM TAB 
          where TAB.field1 =3
           ORDER BY TAB.[creationDate] DESC
          ) AS TEST
     )
Related