SQLUSA
SQL 2005
Business Intelligence Workshop
NYC March 17-20
Register Today!

Microsoft SQL Server 2008 Best Practices

How to find the top & bottom 5 rows in a table?

 

The following T-SQL database script in Query Editor demonstrates the use of the TOP function to get both TOP and BOTTOM of a table in one query.

USE AdventureWorks;

GO

 

SELECT OrderDate = convert(varchar, OrderDate,111)

     , sod.*

    FROM Sales.SalesOrderDetail sod

    INNER JOIN Sales.SalesOrderHeader soh

          ON soh.SalesOrderID = sod.SalesOrderID

    WHERE SalesOrderDetailID IN (

    SELECT TOP 5 SalesOrderDetailID

        FROM Sales.SalesOrderDetail

        ORDER BY SalesOrderDetailID)

        OR

-- Descending sort will give the BOTTOM even though TOP is used

            SalesOrderDetailID IN (

    SELECT TOP 5 SalesOrderDetailID

        FROM Sales.SalesOrderDetail

        ORDER BY SalesOrderDetailID DESC)

       

ORDER BY SalesOrderID

 

GO

 

 

 

SQLUSA - The Best SQL Server 2008 Training in the World
 
 
SQLUSA.com Home Page