You can retrieve a deleted MySQL database on Ubuntu only if a usable copy still exists somewhere: a logical dump, a physical backup, binary logs, a filesystem or disk snapshot, or the original data directory under /var/lib/mysql. If none of those exist, MySQL has no built-in "undelete" command, and your realistic recovery route becomes filesystem-level or professional data recovery. The first thing to do is stop writing to the affected disk, because every new write reduces the odds that deleted files or pages can be reconstructed.
This guide covers each recovery path in order of reliability, with the exact Ubuntu commands and the checks that tell you whether it worked.
Identify What Actually Got Deleted
MySQL data can be lost in three very different ways, and the right fix depends on which one happened.
A dropped database or table (DROP DATABASE, DROP TABLE) removes metadata and usually the underlying files, but the rest of the server keeps running normally. A wiped or reinitialized data directory (reinstall, mysqld --initialize, a botched upgrade) leaves the server unable to start or missing system tables. A filesystem or disk failure takes the whole /var/lib/mysql tree with it.
Recovery also depends on your storage engine. InnoDB stores everything inside ibdata1 and per-table .ibd files and keeps a redo log that can replay committed but unflushed transactions. MyISAM stores each table as separate .MYD/.MYI files with no transaction log. Write the answer down before you touch anything: which server, which database name, when it disappeared, and what changed on the machine around that time. That timeline tells you whether binary logs, snapshots, or backups plausibly cover the loss.
Immediately take a full copy of the surviving data directory before any recovery attempt:
The -a flag preserves ownership and permissions, which matter because MySQL refuses to start on a data directory with the wrong owner.
Check for a Logical Backup First
The fastest, cleanest recovery is a mysqldump or mysqlpump file. On Ubuntu, default package installs don't schedule MySQL backups, so this depends on whether you or your hosting provider set them up. Look in the usual places: /var/backups, /home/*/backups, /root, any mounted backup volume, cron jobs under /etc/cron.d and root's crontab, and Debian's automysqlbackup if installed.
A dump restores into a fresh or existing server without any binary fiddling:
For a compressed dump:
If the dump contains CREATE DATABASE, it restores in place. If it was made with --databases, the USE statements are included. If it was made with a single-database dump and no CREATE DATABASE, create the schema first:
Check success by comparing row counts on your most important tables against the values in the dump, and by running mysqlcheck --check yourdb. A dump is only as fresh as its timestamp, so accept the data-loss window between the dump and the deletion.
If the server is still running and only one database survived in another location (a replica, a staging box, a developer machine), dump it from there with mysqldump --routines --triggers --single-transaction yourdb > yourdb.sql. The --single-transaction flag gives a consistent snapshot for InnoDB without locking writes.
Use Binary Logs for Point-in-Time Recovery
If binary logging was enabled — check with SHOW VARIABLES LIKE 'log_bin'; returning ON — you can replay everything that happened after your last full backup and stop just before the destructive statement. Ubuntu's mysql-server package does not enable binary logging by default, so this only works if someone turned it on.
The procedure, assuming a full backup from before the deletion plus the binlogs:
The --stop-position value comes from the end_log_pos of the event just before the DROP. You can pinpoint the exact coordinate with:
and searching for the statement, then reading the end_log_pos of the preceding event. For row-based logging, DECODE-ROWS shows what changed; for statement-based, the SQL appears plainly.
Check success by comparing a few key table checksums against timestamps you know, then replaying the binlogs further if the data looks stale. One limit: binary logs only cover a rolling window controlled by binlog_expire_logs_seconds (default is 30 days in recent MySQL versions), so a deletion older than that window is not recoverable this way. Binlogs are also written after the server accepts statements, so if the deletion happened during the same burst of writes as your last backup, you may be replaying damage you can't distinguish from good data.
Copy the Old Data Directory Into a Fresh Install
When /var/lib/mysql still exists but the MySQL installation is broken or reinstalled, the data files themselves are often intact. This is the scenario in a widely referenced recovery thread where a sudo apt purge mysql* removed the packages but left /var/lib/mysql in place; the answer there was to install MySQL again and restore the old directory over the new one.
The steps, with safety margins:
1: Stop MySQL: sudo systemctl stop mysql. 2: Back up the current (possibly good) data directory: sudo cp -a /var/lib/mysql /var/lib/mysql.new. 3: Back up the old directory to a separate location: sudo cp -a /var/lib/mysql.old /var/lib/mysql.old.backup. 4: Install or reinstall the matching MySQL version. This matters: an InnoDB data directory is tied to the server's file format and redo log generation. The askubuntu case that failed was exactly a MySQL 5.7 data directory handed to a MySQL 8 server; the upgrade is not a drop-in copy, it's an in-place upgrade that expects the original engine. Match major and minor versions where possible, or plan a proper upgrade path. 5: Set ownership: sudo chown -R mysql:mysql /var/lib/mysql and permissions sudo chmod 750 /var/lib/mysql. 6: Start MySQL: sudo systemctl start mysql. 7: Watch the error log: sudo tail -f /var/log/mysql/error.log.
Check success with SHOW DATABASES;, then SELECT COUNT(*) on a few known tables. If the server won't start, the error log usually names the problem — a missing ib_logfile, a permissions issue, or the wrong --datadir.
The subtlety most guides skip: if you're copying the entire data directory, you're also copying the mysql system database, which holds accounts and grants. If you're copying only a database subdirectory (for example /var/lib/mysql/yourdb), you're bringing table files but not the InnoDB data dictionary that references them, which is why per-database directory copies frequently fail for InnoDB. For InnoDB, the supported way to move tables between servers is mysqldump or mysqlpump on a live server, or transportable tablespaces (ALTER TABLE ... DISCARD TABLESPACE / IMPORT TABLESPACE) when you have .cfg files. Copying raw .ibd files without the accompanying .cfg and dictionary entries is a last resort, not a reliable method.
Rebuild the MySQL System Database
If the mysql system database itself was dropped or corrupted, the server may still start but have no user table, so you can't log in normally. Two recovery options:
On modern MySQL (5.7 and later), mysqld --initialize re-creates the system tables with a fresh root password written to the error log. This is destructive to user accounts but gives you a working server, and then you restore user databases with dumps. On older versions, mysql_install_db does the equivalent.
For a server that refuses to start because mysql database files are inconsistent, use mysqld --initialize-insecure on a separate data directory, then copy user grants over via mysqldump mysql from any surviving copy.
If you need to erase everything and start clean (a last resort), the standard Ubuntu reset is:
Retrieve the temporary root password from the error log (sudo grep 'temporary password' /var/log/mysql/error.log), log in, change it, then restore your databases from dumps.
Check success with mysql -u root -p -e "SELECT user, host FROM mysql.user;" and confirm your application users are present.
Recover Deleted Files From the Filesystem
When there is no dump and no usable data directory copy, you're looking at filesystem-level recovery, which is uncertain and gets worse with every write to the disk.
If the file or directory was deleted normally (rm, DROP DATABASE deletes files), on ext4 with extundelete or on XFS with xfs_undelete (recent XFS kernels support xfs_scrub-adjacent recovery; older versions are harder), you can attempt to recover the deleted .ibd files. The critical constraint: stop writing to that filesystem immediately. Ideally, boot from an Ubuntu live USB, mount the affected disk read-only, and run recovery tools from the live environment. For ext4:
For systems using LVM or a filesystem with snapshots (ZFS, btrfs, LVM thin volumes), a snapshot from before the deletion is the single best recovery source. If you use zfs-auto-snapshot or btrfs snapshots, list them (zfs list -t snapshot or btrfs subvolume list /) and restore the /var/lib/mysql subtree from the closest one before the deletion. A snapshot restore is exact, fast, and needs no MySQL gymnastics.
Check success only after starting a MySQL instance against the recovered files and seeing the expected databases. If InnoDB recovery fails with corruption, do not rinse and repeat on the same files; copy them to a fresh location first.
What Won't Work, and When to Stop
A few common troubleshooting dead ends are worth naming.
No built-in undelete. MySQL has no UNDROP DATABASE and no equivalent to garbage collection or time travel. The concept of dropped-table recovery ends at what backups and logs captured.
InnoDB's recovery mode is about crash recovery, not deleted data. innodb_force_recovery levels 1–6 help a server start when the redo log or data pages are inconsistent after an unclean shutdown. They do not bring back a dropped table, and forcing recovery risks further damage. Use it only for a damaged data directory and always on a copy.
Deleted rows in InnoDB may linger on pages but aren't exposed for you to fetch. MySQL's InnoDB manages delete-marked records internally for MVCC. The exact-page forensic route exists in commercial tools and professional forensics, not in a standard Ubuntu shell session.
Binary log replay after the deletion does not reverse it. People expect to "replay backwards." You can't; you replay forward from a base backup and stop short.
A specific stopping point matters. If the database is business-critical, the disk is a failing SSD, or the files are gone and binary logs don't cover the window, more tinkering reduces your options. Stop, keep an untouched disk image, and bring in a data recovery professional who works with filesystem-level or InnoDB-internals recovery. Continuing to run MySQL, installing packages, and rebuilding the server writes to the same device and can overwrite the data you want.
Reinstall and Restore a Clean Mirror
If the deletion is limited to one database and other files (like its .ibd files and recent binary logs) still exist, the most robust path is often to set up a new MySQL instance on a separate --datadir, point it at a copy of the old data directory, and then mysqldump from that instance. This isolates the recovery work from production, lets you use innodb_force_recovery safely on a copy, and after the recovered dump exists, you can restore onto the production server without further risk.
The sequence is:
1: Copy /var/lib/mysql (or its subdirectories) to a working directory, e.g. /tmp/recover. 2: Initialize a new instance: sudo mysqld --initialize --datadir=/tmp/recover --user=mysql. 3: Start it: sudo mysqld --datadir=/tmp/recover --socket=/tmp/recover.sock --port=3307 --user=mysql. 4: Connect: mysql -S /tmp/recover.sock -u root -p. 5: Confirm tables and then dump: mysqldump -S /tmp/recover.sock -u root -p yourdb > yourdb_recovered.sql. 6: Restore into production from that dump.
This works best on a logically intact data directory — one with consistent data and redo logs — not one that was partly overwritten.
Prevent the Next Deletion From Being Unrecoverable
The recovery steps above work in proportion to what existed before the loss. A daily mysqldump cron job with rotation and off-host storage turns most database deletions into a 10-minute restore. Enabling binary logs (log_bin=ON and a sensible expire_logs window) covers point-in-time recovery between dumps. Filesystem snapshots of /var/lib/mysql add a third layer that catches the case where someone drops and reinitializes the server in one incident.
The practical layering for an Ubuntu server is: automated mysqldump or mysqlpump every night, binary logs retained longer than your dump interval, and ZFS or btrfs snapshots of the data directory at least daily. On request, a single SELECT from a shell alias gets you a fresh dump before a risky migration; a separate account with RELOAD, LOCK TABLES, SHOW VIEW, EVENT, TRIGGER, PROCESS privileges (not the application user) makes backups independent of app changes.
If you're using managed hosting or cloud database services, check whether point-in-time recovery is enabled and how far back it reaches — that's the fastest recovery route you have, and it isn't controlled by anything you do in the Ubuntu shell.
When the answer is "nothing was backed up and the files are gone," the honest answer is that MySQL on Ubuntu can't retrieve a deleted database from nothing. You can still recover data from the disk, from old copies elsewhere, or from storage snapshots if they exist, and you should stop work on the disk while those options are explored.