Title: Selecting the Nth row from a SQL table
Slug: selecting-the-nth-row-from-a-sql-table
Date: 2007-04-23 13:32:00
Author: Kartones
Lang: en
Tags: Databases, SQL, Development
Description: A guide on selecting the Nth row from a SQL table.

 <p>Yesterday I had to find a way to get the second row in a SQL query (but the same can be applied  to a table). But it should be clean and should work with the  third row, fourth, and so on.</p> <p>We start by having this table:</p> <p><img title="SQL table design" alt="SQL table design" src="https://images.kartones.net/posts/screenshots/sql_nth_row_example01.jpg"></p> <p>And this starting data:</p> <p><img title="SQL table data" alt="SQL table data" src="https://images.kartones.net/posts/screenshots/sql_nth_row_example02.jpg"></p> <p>And this is the SQL  query that would give us the 2nd row of that table  (<b>[34, 1]</b> with our sample data):</p> <p><font face="Courier New"><font color="#0000ff">SELECT</font> <br>    <font color="#0000ff">TOP</font> 1 NumberOfPosts, UserId <br><font color="#0000ff">FROM</font> <br>    (<br>    <font color="#0000ff">SELECT</font> <br>        <font color="#008000">-- Here change the "2" for the desired Nth position</font></font><font face="Courier New"><br>        <font color="#0000ff">TOP</font> 2 NumberOfPosts, UserId <br>    <font color="#0000ff">FROM</font> <br>        TopBloggers <br>    <font color="#0000ff">ORDER BY</font> <br>        NumberOfPosts <font color="#0000ff">DESC</font><br>    ) <font color="#0000ff">AS</font> NPOSTS<br><font color="#0000ff">ORDER BY</font> <br>    NumberOfPosts</font></p>
