Link to home
Start Free TrialLog in
Avatar of JoeSnyderJr
JoeSnyderJrFlag for United States of America

asked on

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
Avatar of Guy Hengel [angelIII / a3]
Guy Hengel [angelIII / a3]
Flag of Luxembourg image

this should do:
delete from logtable 
where pkeyid in (select top(10000) pkeyid from logtable order by pkeyid desc)

Open in new window

Avatar of JoeSnyderJr

ASKER

Sorry but that is going to delete the most current 10000 records. I am attempting to delete records NOT in that set.
delete from logtable
where pkeyid not in (select top(10000) pkeyid from logtable order by pkeyid desc)
Granted this will work but won't this be a resource hog compared to delete where pkeyID < TOP(1)
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

Sorry to be a pain but don't recognize meaning for seqment ') sp' and get syntax error on line 7 near 'asc'
ASKER CERTIFIED SOLUTION
Avatar of Guy Hengel [angelIII / a3]
Guy Hengel [angelIII / a3]
Flag of Luxembourg image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
PERFECT!  Thanks much for prompt assistance. No wonder you are consistently at top of assistance list.