Click here to Skip to main content
15,894,017 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello, i need to know how to retrieve only the second row value from the database table.

for example, to retrieve the first row, i used:

SELECT TOP(1) FROM tablename;

but how do i retrieve the second row? i tried using the "SELECT TOP(2) FROM tablename" but it return me the first and second row.

but i only want the second row data. how can i achieve this?
Posted
Comments
Zoltán Zörgő 28-Jun-13 14:14pm    
What is the ordering? You should have since the rows in a table are by definition not ordered, thus "first" and "second" have no standard meaning without order.

Try this:
SQL
SELECT TOP(1) T.*
FROM (
    SELECT TOP(2)
    FROM tablename
    ORDER BY ID DESC 
) AS T


or
SQL
SELECT T.*
FROM (
    SELECT *, ROW_NUMBER() OVER(ORDER BY ID) AS RowNo
    FROM tablename
) AS T
WHERE RowNo = 2
 
Share this answer
 
Comments
Jerrell77 29-Jun-13 11:51am    
any idea why i can run the codes in the Query builder but they show me the error "the dataset in the objectdatasource does not contain any tables" when i place the codes in the DAL?
Maciej Los 30-Jun-13 4:23am    
Without code - NO!
Please, post new question and share your code.
SQL does not have to return rows in any particular order, so you have to specify an ordering if you want to fetch any specific row. However, when you have done that, try this:
SQL
WITH myTableWithRows AS (
     SELECT (ROW_NUMBER() OVER (ORDER BY myTable.SomeField)) as row,*
     FROM myTable)
SELECT * FROM myTableWithRows WHERE row = 2
 
Share this answer
 
Comments
Jerrell77 29-Jun-13 11:51am    
any idea why i can run the codes in the Query builder but they show me the error "the dataset in the objectdatasource does not contain any tables" when i place the codes in the DAL?
OriginalGriff 29-Jun-13 12:01pm    
Nope! :laugh:
Have a look at your DAL code, or step into it and see what it does with your query.
Jerrell77 29-Jun-13 12:42pm    
the over construct or statement is not supported. any idea why?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900