MySQL – How to Recover Truncated Table

MySQL

I am getting the "wrong input table name" when use TRUNCATE as following:

TRUNCATE `stats`

The table should bans.

How to recover stats table?

I am using CentOS 6, and MySQL-Server.

Best Answer

If you have binary logging enabled, you can replay changes that went into creating the stats table, up to the point where you did the TRUNCATE.

But you may not have binary logs for all changes to that table from the beginning of time. It's common to have binary logs only back a few days. Any data that was created in that table prior to your oldest binary log is not recoverable.

Figuring out the location in the binary log where you need to stop replaying (the TRUNCATE statement) is a bit tricky. Basically, use mysqlbinlog to dump the contents of that log as a SQL script, then open that script in an editor and delete everything from the TRUNCATE statement to the end.

See also https://dev.mysql.com/doc/refman/5.6/en/point-in-time-recovery.html for more tips on using mysqlbinlog for recovery.

Replaying only the changes to one specific table is also a bit tricky. Here's one solution proposed by long-time MySQL expert Giuseppe Maxia: http://datacharmer.blogspot.com/2010/11/filtering-binary-logs-with-mysql.html

You could also filter the SQL script produced from the binary log using pt-query-digest, and find only log events that reference your stats table.

If you don't have binary logs back far enough, none of that will help though. You could try to use an undelete tool for your filesystem (you don't say if you're on Linux or Windows or other), but the longer you wait, the more likely the space on disk is going to be recycled and used for other files.

i can't recover from .frm file? – Putra Fajar Hasanuddin Mar 12 at 6:20

No, the .frm file contains only the table definition, but no data. And since you just used TRUNCATE TABLE and not DROP TABLE, you still have easy access to the table definition anyway.

I'm sorry if you have suffered unrecoverable data loss, but I hope this has at least convinced you of the importance of regular database backups.

Related Question