How to locate nth item in an MSSQL table

I have a log table. Once table has > 10000 row in the table I need to remove earliest rows created until table contains no more than 10000 rows.

I am attempting to create delete query that will meet this requirement.

Have attempted with:
delete from logtable where pkeyid < (select top(1) pkeyid from
(select top (10000) pkeyid from logtable)  order by pkeyid desc))

but MSSql report syntax errors for this attempt

Looking for corrections to my query or alternate providing same solution results
JoeSnyderJrAsked:
Who is Participating?
 
Guy Hengel [angelIII / a3]Billing EngineerCommented:
ousp
delete from logtable 
  where pkeyid < ( select top 1 pkeyid 
                     from ( select top 10000 pkeyid 
                              from logtable order by pkid desc 
                          ) sq  
                     order by pkeyid asc
                  ) 

Open in new window

0
 
Guy Hengel [angelIII / a3]Billing EngineerCommented:
this should do:
delete from logtable 
where pkeyid in (select top(10000) pkeyid from logtable order by pkeyid desc)

Open in new window

0
 
JoeSnyderJrAuthor Commented:
Sorry but that is going to delete the most current 10000 records. I am attempting to delete records NOT in that set.
0
Ultimate Tool Kit for Technology Solution Provider

Broken down into practical pointers and step-by-step instructions, the IT Service Excellence Tool Kit delivers expert advice for technology solution providers. Get your free copy now.

 
Guy Hengel [angelIII / a3]Billing EngineerCommented:
delete from logtable
where pkeyid not in (select top(10000) pkeyid from logtable order by pkeyid desc)
0
 
JoeSnyderJrAuthor Commented:
Granted this will work but won't this be a resource hog compared to delete where pkeyID < TOP(1)
0
 
Guy Hengel [angelIII / a3]Billing EngineerCommented:
that can only be answered by checking the explain plan vs the timing of the queries under similar environments...

your syntax error, btw, was here:
delete from logtable 
  where pkeyid < ( select top 1 pkeyid 
                     from ( select top 10000 pkeyid 
                              from logtable order by pkid desc 
                          ) sq  
                     order by pkeyid asc
                  ) asc

Open in new window

0
 
JoeSnyderJrAuthor Commented:
Sorry to be a pain but don't recognize meaning for seqment ') sp' and get syntax error on line 7 near 'asc'
0
 
JoeSnyderJrAuthor Commented:
PERFECT!  Thanks much for prompt assistance. No wonder you are consistently at top of assistance list.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.