Saturday, May 2, 2009

Selecting top, bottom and in between rows in sql

In this post I am going to show how you in an easy way can select top, bottom and in between rows from a table. The table that I am using is a fictitious Customer table with primary key name CustomerID.

1. Selecting the first 10 rows from Customer table:

SELECT TOP 10 * FROM Customer ORDER BY CustomerID

The code above is quite straight forward using the "TOP" keyword to picking out the first 10 rows.

2. Selecting the bottom 10 rows from Customer table:

SELECT TOP 10 * FROM Customer ORDER BY CustomerID DESC

In this code we also use the "TOP" keyword but now we change the sort order to "DESC" (descenging) letting us picking out the 10 rows from the bottom.

3. Selecting rows between 10-20 from Customer table:

SELECT TOP 10 * FROM Customer WHERE CustomerID IN
(
SELECT TOP 20 CustomerID FROM Customer ORDER BY CustomerID
) ORDER BY CustomerID DESC

In the code above we use nestled query to achieve the extraction of row 10-20. The inner query picks out row 0-20 and the outer query picks out row 10-20 from the inner query.

No comments:

Post a Comment

get a counter