sqlsql-servert-sqlsql-server-administration

SQL Batched Delete


I have a table in SQL Server 2005 which has approx 4 billion rows in it. I need to delete approximately 2 billion of these rows. If I try and do it in a single transaction, the transaction log fills up and it fails. I don't have any extra space to make the transaction log bigger. I assume the best way forward is to batch up the delete statements (in batches of ~ 10,000?).

I can probably do this using a cursor, but is the a standard/easy/clever way of doing this?

P.S. This table does not have an identity column as a PK. The PK is made up of an integer foreign key and a date.


Solution

  • You can 'nibble' the delete's which also means that you don't cause a massive load on the database. If your t-log backups run every 10 mins, then you should be ok to run this once or twice over the same interval. You can schedule it as a SQL Agent job

    try something like this:

    DECLARE @count int
    SET @count = 10000
    
        DELETE  FROM table1 
        WHERE table1id IN (
            SELECT TOP (@count) tableid
            FROM table1
            WHERE x='y'
        )