Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL - Delete table with 372 million rows starting from first row

I have a table with 372 million rows, I want to delete old rows starting from the first ones without blocking the DB. How can I reach that?

The table have

id | memberid | type |      timeStamp          | message |
1     123        10    2014-03-26 13:17:02.000    text

UPDATE:

I deleted about 30 GB of Space in DB, but my DISC is ON 6gb space yet.. Any suggestion to get that free space?

Thank you in advance!

like image 316
Funereal Avatar asked May 11 '16 08:05

Funereal


People also ask

How do I delete 10000 rows in SQL?

If you need to remove 10 million rows and have 1 GB of log space available use Delete TOP(10000) From dbo. myTable (with your select clause) and keep running it till there are no more rows to delete.

How do you bulk delete rows in SQL?

Another way to delete multiple rows is to use the IN operator. DELETE FROM table_name WHERE column_name IN (value 1, value 2, value 3, etc...); If you want to delete all records from the table then you can use this syntax.

How can I delete 1000 rows limit in SQL Server?

On the menu bar visit Edit -> Preferences . Expand SQL Editor . Select SQL Execution . In the SELECT Query Results section, you can either uncheck Limit Rows or increase/decrease the Limit Rows Count.


2 Answers

select 1;
while(@@ROWCOUNT > 0)
begin
   WAITFOR DELAY '00:00:10';
   delete top(10) from tab  where <your-condition>;

end

delete in chunks using above sql

like image 103
Akshey Bhat Avatar answered Sep 17 '22 14:09

Akshey Bhat


You may want to consider another approach:

  1. Create a table based on the existing one
  2. Adjust the identity column in the empty table to start from the latest value from the old table (if there is any)
  3. Swap the two tables using sp_rename
  4. Copy the records in batches into the new table from the old table
  5. You can do whatever you want with the old table.

BACKUP your database before you start deleting records / play with tables.

like image 26
Pred Avatar answered Sep 17 '22 14:09

Pred