How to purge all but the top N rows from a table

  • I tried asking this question on AskSqlServerCentral, but I think its undergoing PM work now, so please bear with me.

    I've got a simple table, with the following structure:

    CREATE TABLE LastUpdates (

    LastUpdateID int IDENTITY(1,1) NOT NULL,

    DateLastUpdated datetime NOT NULL,

    CONSTRAINT PK_LastUpdates PRIMARY KEY CLUSTERED

    (

    LastUpdateID ASC

    )

    ) ON PRIMARY

    What I want to be able to do is purge all but the latest 10 records or so, based upon the DateLastUpdated value. How do I go about doing that?

    Kindest Regards, Rod Connect with me on LinkedIn.

  • Here's one way.

    I can think of at least one other.

    DELETE FROM LastUpdates

    WHERE LastUpdateID NOT IN

    (

    SELECT TOP 10 LastUpdateID

    FROM LastUpdates

    ORDER BY DateLastUpdated DESC)

  • If it is a lot of data and you do not want the overhead of deletes, I would insert the 10 rows you want to keep into a temp table, truncate the existing, and then insert back in. Depends on how much data you have and if you need to delete these rows as output.

    Jared
    CE - Microsoft

  • Thank you, MysteryJimbo, that looks like it will work.

    Kindest Regards, Rod Connect with me on LinkedIn.

  • At this point I don't have any data at all in the table, SQLKnowItAll, so I can be flexible as to how I handle this.

    Kindest Regards, Rod Connect with me on LinkedIn.

  • Rod at work (2/1/2012)


    At this point I don't have any data at all in the table, SQLKnowItAll, so I can be flexible as to how I handle this.

    In that case, don't do deletes. 😉

    --Jeff Moden


    RBAR is pronounced "ree-bar" and is a "Modenism" for Row-By-Agonizing-Row.
    First step towards the paradigm shift of writing Set Based code:
    ________Stop thinking about what you want to do to a ROW... think, instead, of what you want to do to a COLUMN.

    Change is inevitable... Change for the better is not.


    Helpful Links:
    How to post code problems
    How to Post Performance Problems
    Create a Tally Function (fnTally)

Viewing 6 posts - 1 through 5 (of 5 total)

You must be logged in to reply to this topic. Login to reply