Solved

select Nth row from table

Posted on 2002-05-10
3
229 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:
ScottPletcher 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:ScottPletcher
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

What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

Slowly Changing Dimension Transformation component in data task flow is very useful for us to manage and control how data changes in SSIS.
International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
This videos aims to give the viewer a basic demonstration of how a user can query current session information by using the SYS_CONTEXT function
Viewers will learn how to use the SELECT statement in SQL to return specific rows and columns, with various degrees of sorting and limits in place.

757 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

Need Help in Real-Time?

Connect with top rated Experts

18 Experts available now in Live!

Get 1:1 Help Now