Solved

select Nth row from table

Posted on 2002-05-10
3
233 Views
Last Modified: 2008-03-06
I have a table with a billion rows
id (primary key, identity), email, firstname, etc...

I want to grab a specific row number, but the id's have gaps (from deleting rows)

my first attempt:
select top 1 * from mytable e where (select count(id) from mytable where id <= e.id) = 412

that would return the 412th row regardless of gaps in id.. the problem with that query is its sooo slow!

can anyone help me with a better solution?

maybe a better idea would be to re-index the table whenever a row is deleted but I could not figure out how to do that either (without making a temporary table) BTW: no temp tables.. the table is toooo BIG to be duplicated
0
Comment
Question by:gfody
  • 2
3 Comments
 
LVL 69

Accepted Solution

by:
Scott Pletcher earned 200 total points
ID: 7002151
If you're going after a relatively low-numbered row, such as 412, this should work OK:

SELECT TOP 1 *
FROM
(SELECT TOP 412 *
FROM myTable
ORDER BY id) AS topOfMyTable
ORDER BY id DESC
0
 
LVL 69

Expert Comment

by:Scott Pletcher
ID: 7002159
Naturally you will need an index on id (as the first/only column in the index) for this to run efficiently.  You should probably remove it from the other index unless it's needed there to specify order.

Also, since the TOP clause will not accept a variable, with this method you would have to use sp_executesql or EXEC('SELECT ...') to make the row number dynamic.
0
 
LVL 2

Author Comment

by:gfody
ID: 7002321
thank you, this is much faster
0

Featured Post

VMware Disaster Recovery and Data Protection

In this expert guide, you’ll learn about the components of a Modern Data Center. You will use cases for the value-added capabilities of Veeam®, including combining backup and replication for VMware disaster recovery and using replication for data center migration.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction In my previous article (http://www.experts-exchange.com/Microsoft/Development/MS-SQL-Server/SSIS/A_9150-Loading-XML-Using-SSIS.html) I showed you how the XML Source component can be used to load XML files into a SQL Server database, us…
Slowly Changing Dimension Transformation component in data task flow is very useful for us to manage and control how data changes in SSIS.
Using examples as well as descriptions, and references to Books Online, show the documentation available for date manipulation functions and by using a select few of these functions, show how date based data can be manipulated with these functions.
Via a live example, show how to set up a backup for SQL Server using a Maintenance Plan and how to schedule the job into SQL Server Agent.

809 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question