//  home   //  advanced search   //  news   //  categories   //  sql build chart   //  downloads   //  statistics
 ASP FAQ 
Home
ASP FAQ Tutorials

   8000XXXX Errors
   ASP.NET 2.0
   Classic ASP 1.0
   Databases
      Access DB & ADO
      General SQL Server & Access Articles
      MySQL
      Other Articles
      Schema Tutorials
      Sql Server 2000
      Sql Server 2005
   General Concepts
   Search Engine Optimization (SEO)

Contact Us
Site Map

Search

Web
aspfaq.com
tutorials.aspfaq.com
sqlserver2000.databases.aspfaq.com

ASP FAQ Tutorials :: Databases :: Sql Server 2000 :: How do I get the nth row in a SQL Server table?


How do I get the nth row in a SQL Server table?

You might have occasion where you want to discover who finished second, the 10th most popular rock song, or the 5th highest paid employee. This is trival using nested TOP statements, but those can get pretty heavy if you are trying to get row 5,199,245. Here are some other options you can test (turn statistics and execution plan on, and test against large resultsets, to see the impact of the methods in different scenarios). This example assumes a unique FName, and tries to get the 10th name (in alphabetical order). 
 
CREATE TABLE Names 

    NameID INT IDENTITY(1, 1) 
        PRIMARY KEY CLUSTERED, 
    FName VARCHAR(32) 

GO 
 
SET NOCOUNT ON 
INSERT Names(FName) VALUES('Aaron') 
INSERT Names(FName) VALUES('Greg') 
INSERT Names(FName) VALUES('Alex') 
INSERT Names(FName) VALUES('Luan') 
INSERT Names(FName) VALUES('John') 
INSERT Names(FName) VALUES('Todd') 
INSERT Names(FName) VALUES('Scott') 
INSERT Names(FName) VALUES('Jess') 
INSERT Names(FName) VALUES('Drew') 
INSERT Names(FName) VALUES('Katherine') 
INSERT Names(FName) VALUES('Paul') 
GO 
 
-- solution #1: nested top 
 
SELECT TOP 1 FName 
FROM 

    SELECT TOP 10 FName 
    FROM Names 
    ORDER BY FName 
) sub 
ORDER BY FName DESC 
 
-- solution #2: NOT IN 
 
SELECT TOP 1 FName  
FROM Names WHERE FName NOT IN 

    SELECT TOP 9 FName 
    FROM Names 
    ORDER BY FName 

ORDER BY FName 
 
-- solution #3: derived count 
-- this assumes FName is unique 
 
SELECT FName 
    FROM Names 
    WHERE  
    ( 
        SELECT COUNT(*) 
        FROM Names n2 
        WHERE n2.FName <= Names.FName 
    ) = 10 
 
-- solution #4: MAX 
 
SELECT FName = MAX(FName) FROM  

    SELECT TOP 10 FName 
    FROM Names 
    ORDER BY FName 
) sub 
 
-- solution #5: relative fetch from cursor 
 
-- yes, cursors are generally evil, but 
-- sometimes you might be surprised 
 
DECLARE FNames CURSOR 
    LOCAL STATIC READ_ONLY FOR 
    SELECT FName 
        FROM Names 
        ORDER BY FName 
 
DECLARE @FName VARCHAR(32) 
 
OPEN FNames 
 
FETCH RELATIVE 10 FROM FNames INTO @FName 
 
CLOSE FNames 
DEALLOCATE FNames 
 
SELECT FName = @FName 
 
DROP TABLE Names 
GO
 
There are two issues that the above queries don't take into account: what if there are duplicates (ties)? and what if we want more data than the column we are ordering by? Here are some more examples. This is an employees table, and we want the employee(s) with the 7th highest salary. 
 
CREATE TABLE Employees 

    EmployeeID INT IDENTITY(1, 1) 
        PRIMARY KEY CLUSTERED, 
    LName VARCHAR(32), 
    Salary INT 

GO 
 
SET NOCOUNT ON 
INSERT Employees(LName, Salary) VALUES('Bertrand', 350000) 
INSERT Employees(LName, Salary) VALUES('Le' , 40000) 
INSERT Employees(LName, Salary) VALUES('Smith' , 50000) 
INSERT Employees(LName, Salary) VALUES('Weathers', 80000) 
INSERT Employees(LName, Salary) VALUES('Martin' , 53000) 
INSERT Employees(LName, Salary) VALUES('VanWyck' , 32000) 
INSERT Employees(LName, Salary) VALUES('Gretzky' , 30000) 
INSERT Employees(LName, Salary) VALUES('Jambon' , 30000) 
INSERT Employees(LName, Salary) VALUES('DeNiro' , 50000) 
INSERT Employees(LName, Salary) VALUES('Albert' , 40000) 
INSERT Employees(LName, Salary) VALUES('Willis' , 70000) 
 
-- solution #1: nested top, take aribitrary row 
 
SELECT TOP 1 LName, Salary 
FROM 

SELECT TOP 7 
    LName, Salary FROM Employees 
    ORDER BY Salary DESC 
) sub 
ORDER BY Salary 
 
-- solution #2: nested top, order by lastname 
 
SELECT TOP 1 LName, Salary 
FROM 

SELECT TOP 7 
    LName, Salary FROM Employees 
    ORDER BY Salary DESC, LName 
) sub 
ORDER BY Salary 
 
-- solution #3: nested top, take both rows 
 
SELECT TOP 1 WITH TIES LName, Salary 
FROM 

SELECT TOP 7 WITH TIES 
    LName, Salary FROM Employees 
    ORDER BY Salary DESC 
) sub 
ORDER BY Salary 
 
-- solution #4: NOT IN, take both rows 
 
SELECT TOP 1 WITH TIES LName, Salary 
    FROM Employees e 
    WHERE Salary NOT IN 
    ( 
        SELECT TOP 6 WITH TIES Salary 
        FROM Employees 
        ORDER BY Salary DESC 
    ) 
    ORDER BY e.Salary DESC 
 
-- solution #5: change NOT IN to OUTER JOIN 
 
SELECT TOP 1 WITH TIES e.LName, e.Salary 
    FROM Employees e 
    LEFT OUTER JOIN 
    ( 
        SELECT TOP 6 WITH TIES Salary 
        FROM Employees 
        ORDER BY Salary DESC 
    ) e2 
    ON e.Salary = e2.salary 
    WHERE e2.salary IS NULL  
    ORDER BY e.Salary DESC 
 
DROP TABLE Employees 
GO
 
Finally, check out this generic procedure from Vyas, which uses dynamic SQL to get the nth row out of any table, based on any column. 
 
With Access, some of the above queries might work. Or, you could just repeatedly hit rs.movenext until you arrive at the requested row. Finally, you could stuff the result into a GetRows array and move to the desired position. 
 
Keep in mind that there is no 'FIRST' functionality in SQL Server. There is no concept of 'FIRST' or 'LAST' like in Access, unless you specifically say you want TOP 1 or MAX and add an ORDER BY clause. Unlike Access, which assumes there is some meaning to the physical ordering of the data on disk, SQL Server treats a set of data exactly like that - a set of unordered data. If you want it in a specific order, you have to ask for it that way.

Related Articles

Are there tools available for auditing changes to SQL Server data?
Can I create an index on a BIT column?
Can I have optional parameters to my stored procedures?
Can I implement an input mask in SQL Server?
Can I make SQL Server format dates and times for me?
Can I start IDENTITY values at a new seed?
Can SQL Server tell me which row was inserted most recently?
How can I learn more about undocumented SQL Server stored procedures?
How can I make my SQL queries case sensitive?
How do I audit changes to SQL Server data?
How do I connect to a non-default instance of SQL Server?
How do I connect to SQL Server on a port other than 1433?
How do I create a cross-tab (or "pivot") query?
How do I determine if a table exists in a SQL Server database?
How do I drop a SQL Server database?
How do I find all the available SQL Servers on my network?
How do I get a list of SQL Server tables and their row counts?
How do I get rid of Named Pipes / DBNMPNTW errors?
How do I get the correct date/time from the msdb.sysjob* tables?
How do I get the result of dynamic SQL into a variable?
How do I handle REPLACE() within an NTEXT column in SQL Server?
How do I hide system tables in SQL Server's Enterprise Manager?
How do I know which version of SQL Server I'm running?
How do I limit the number of rows returned in my resultset?
How do I load text or csv file data into SQL Server?
How do I manage changes in SQL Server objects?
How do I monitor SQL Server performance?
How do I prevent linked server errors?
How do I reclaim space in SQL Server?
How do I recover data from SQL Server's log files?
How do I search for special characters (e.g. %) in SQL Server?
How do I start SQL Server Agent from ASP?
How do I time my T-SQL code?
How do I upsize from Access to SQL Server?
How do I upsize my MSDE database to full-blown SQL Server 2000?
How do I use a variable in a TOP clause in SQL Server?
How do I use GETDATE() within a User-Defined Function (UDF)?
How should I store an IP address in SQL Server?
Schema: How do I find all the foreign keys in a database?
SQL Server & MSDE
What are reserved Access, ODBC and SQL Server keywords?
What are the capacities of Access, SQL Server, and MSDE?
What are the main differences between Access and SQL Server?
What do I need to know about SQL Server 2000 SP4?
Where else can I learn about SQL Server?
Where is SP4 for SQL Server 2000?
Why am I having problems with SQL Server 2000 SP3 / SP3a?
Why can't I install SQL Server on Windows Server 2003?
Why can't I install SQL Server on Windows XP?
Why can't I use LIKE '%datepart%' queries?
Why do I get "Login failed for user '\'."?
Why do I get 'object could not be found' or 'invalid object name'?
Why do I get errors about master..spt_values?
Why do I get script errors in Enterprise Manager's 'taskpad' view?
Why do I get SQLSetConnectAttr Failed errors?
Why do I have problems with views after altering the base table?
Why does EM crash when I get an error in a stored procedure?
Why does Enterprise Manager return 'Invalid cursor state'?
Why does my DELETE query not work?
Why does sp_spaceused return inaccurate values?
Why is Enterprise Manager slow at expanding my database list?
Why is my app slow after upgrading from SQL Server 7 to 2000?
Why is tempdb full, and how can I prevent this from happening?
Why should I consider using an auxiliary calendar table?
Why should I consider using an auxiliary numbers table?

 

 


Created: 2/5/2003 | Last Updated: 12/13/2003 | broken links | helpful | not helpful | statistics
© Copyright 2006, UBR, Inc. All Rights Reserved. (175)

 

Copyright 1999-2006, All rights reserved.
Finding content
Finding content.  An error has occured...