Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Quickest way to delete enormous MySQL table

Tags:

mysql

innodb

I have an enormous MySQL (InnoDB) database with millions of rows in the sessions table that were created by an unrelated, malfunctioning crawler running on the same server as ours. Unfortunately, I have to fix the mess now.

If I try to truncate table sessions; it seems to take an inordinately long time (upwards of 30 minutes). I don't care about the data; I just want to have the table wiped out as quickly as possible. Is there a quicker way, or will I have to just stick it out overnight?

like image 976
Kyle Kaitan Avatar asked May 18 '09 19:05

Kyle Kaitan


People also ask

How can I delete MySQL faster?

1) Run your delete statements with a LIMIT clause (Eg 1000) in a loop until the table is empty, if your deleting a lot. This causes the delete statement transaction to do less work per run.

What is the best method to delete a table having huge data say 100K records?

If you want to delete the records of a table with a large number of records but keep some of the records, You can save the required records in a similar table and truncate the main table and then return the saved records to the main table.


2 Answers

(As this turned up high in Google's results, I thought a little more instruction might be handy.)

MySQL has a convenient way to create empty tables like existing tables, and an atomic table rename command. Together, this is a fast way to clear out data:

CREATE TABLE new_foo LIKE foo;  RENAME TABLE foo TO old_foo, new_foo TO foo;  DROP TABLE old_foo; 

Done

like image 134
searlea Avatar answered Sep 20 '22 11:09

searlea


The quickest way is to use DROP TABLE to drop the table completely and recreate it using the same definition. If you have no foreign key constraints on the table then you should do that.

If you're using MySQL version greater than 5.0.3, this will happen automatically with a TRUNCATE. You might get some useful information out of the manual as well, it describes how a TRUNCATE works with FK constraints. http://dev.mysql.com/doc/refman/5.0/en/truncate-table.html

EDIT: TRUNCATE is not the same as a drop or a DELETE FROM. For those that are confused about the differences, please check the manual link above. TRUNCATE will act the same as a drop if it can (if there are no FK's), otherwise it acts like a DELETE FROM with no where clause.

EDIT: If you have a large table, your MariaDB/MySQL is running with a binlog_format as ROW and you execute a DELETE without a predicate/WHERE clause, you are going to have issues to keep up the replication or even, to keep your Galera nodes running without hitting a flow control state. Also, binary logs can get your disk full. Be careful.

like image 27
womp Avatar answered Sep 19 '22 11:09

womp