To recover a SQL file from the command line, first decide what "recover" means in your situation: bringing a deleted or corrupted .sql dump back from disk, re-importing a dump into a database server, or repairing a damaged MySQL/PostgreSQL data directory so the server can export a fresh dump. The correct tool chain differs for each, and running the wrong one (for example, re-importing a partial dump over a live database) can destroy the data you were trying to save. The steps below are ordered from safest and most reversible to most invasive, so you can stop as soon as you have a valid file.

First, diagnose what actually happened before touching anything

"Recover a SQL file" gets used for at least four different failures, and the fix depends on which one you have. Sorting that out takes a minute and prevents most data loss.

Deleted file, disk otherwise healthy. The .sql file was removed with rm, an editor overwrote it, or a backup script cleaned it up. On most Linux filesystems the file's blocks are still on disk until something else claims them, so the priority is to stop writing to that filesystem immediately. If the database is running on the same disk, stop the database service (sudo systemctl stop mysql or postgresql) so it stops writing.

Truncated or corrupted dump. The file exists but imports fail partway, or the tail is cut off mid-INSERT. Common causes are a full disk during mysqldump, an interrupted scp, or a text-mode FTP transfer that mangled line endings.

Damaged database you need to export from. The server won't start, or tables report corruption. Here the .sql file doesn't exist yet—you're trying to produce one from a broken data directory.

File recovered but unusable as-is. You found the bytes but the encoding, line endings, or statement delimiters are wrong.

Check which one you have with a few read-only commands. For a supposedly deleted file, confirm it's really gone and check free space:

For a damaged dump, confirm its size and tail are sane:

If the last line is a complete INSERT or COMMIT;, the file is probably intact and the problem is elsewhere. If it ends mid-statement, you have a truncated dump and the recovery path is "salvage what's there," covered below.

Stop writes and recover a deleted file from the filesystem

Once you've confirmed the file is deleted and the disk is healthy, the sequence is: stop writes, work from a copy, then attempt undelete. Do not install recovery tools onto the same partition—download them elsewhere or use a live USB.

1: Unmount or remount read-only. For a non-root partition: sudo umount /dev/sdb1. If it's the root filesystem, boot from a live USB instead; remounting root read-only while services run is unreliable on most desktop distributions. 2: Image the partition first. sudo dd if=/dev/sdb1 of=/mnt/external/disk.img bs=4M status=progress. All further work happens on the image, so a mistake never touches the original. 3: Run an undelete tool against the image. extundelete works on ext3/ext4: sudo extundelete /mnt/external/disk.img --restore-file path/to/backup.sql. testdisk/photorec cover broader filesystem and file-type cases; photorec carves by signature, and .sql files are plain text with no magic header, so carving usually fails—prefer filesystem-aware tools. 4: Check the result. Open the recovered file and confirm the tail is complete, as above. Expect partial recovery on ext4 with journaling and delayed allocation; success drops sharply once the filesystem has been written to.

On macOS, tmutil and Time Machine are the realistic path; on Windows, wbadmin or file history before any third-party tool. The principle is the same: snapshot first, recover from the snapshot.

The stop condition here is physical. If the drive makes clicking or grinding noises, or dmesg shows I/O errors, power it down and hand it to a data-recovery service. Software attempts on failing hardware reduce the odds of professional recovery.

If the goal is a fresh dump from a running server, use the native export tool

Sometimes the "SQL file" you want is the one you never made. Both major open-source servers export consistent text dumps, and doing this is also the correct first move before attempting any repair.

For MySQL or MariaDB, the standard logical dump is:

--single-transaction wraps the read in a repeatable-read transaction, giving a consistent snapshot of InnoDB tables without locking writers. It does not work for MyISAM tables, which need --lock-tables. Add --set-gtid-purged=OFF if you'll restore to a server with different GTID settings, and --default-character-set=utf8mb4 to avoid mojibake on non-ASCII data.

For PostgreSQL, use pg_dump:

The custom format (-Fc) is compressed, supports parallel restore with pg_restore -j, and is more robust than plain SQL for large databases. If you specifically need plain SQL, use pg_dump -Fp -f mydb.sql mydb. Note that plain pg_dump does not include roles or tablespaces; pg_dumpall --globals-only captures those separately.

Success check: the file is non-empty, its tail ends with a complete statement, and a test import into a scratch database succeeds. For MySQL, mysql -e "CREATE DATABASE test_restore" then mysql test_restore < mydb_backup.sql catches most problems before they matter.

Re-import a dump safely—and never over the live database first

A recovered dump is only useful if it imports. Import into an isolated database first; only promote it after verification. This is the step people skip, and it's where a "recovered" file overwrites good production data.

For MySQL:

1: Create a scratch database: mysql -u root -p -e "CREATE DATABASE verify_db CHARACTER SET utf8mb4". 2: Import: mysql -u root -p verify_db < mydb_backup.sql. 3: Check row counts on the largest tables against the source: mysql -u root -p -e "SELECT COUNT(*) FROM verify_db.orders". 4: Only after counts match, restore to the real target—ideally after taking a fresh dump of it.

For PostgreSQL, pg_restore reports errors per object and continues, which is useful but easy to misread. Use pg_restore -d verify_db mydb.dump and capture stderr; a non-zero exit means at least one object failed, and the log names it. Plain-SQL dumps restore with psql -d verify_db -f mydb.sql.

Set ON_ERROR_STOP=1 for MySQL (mysql --force is the opposite of what you want during verification) and psql -v ON_ERROR_STOP=1 for PostgreSQL so a failure halts rather than cascading. If the import dies on a foreign-key constraint, load with SET FOREIGN_KEY_CHECKS=0; (MySQL) or --disable-triggers (PostgreSQL, superuser only), then re-enable and validate.

Salvage a truncated or corrupted dump

A dump that stops mid-statement can often be salvaged up to the last complete statement. The approach is mechanical: find where it breaks, cut cleanly, and import the good prefix.

1: Locate the break. For MySQL dumps, statements end with ; at line ends. grep -n ";" mydb.sql | tail -1 gives the last line with a terminator. For PostgreSQL plain dumps, look for the last COPY ... FROM stdin; block's terminating . line. 2: Truncate to the last good statement. head -n <last_good_line> mydb.sql > mydb_fixed.sql. Verify the new tail ends with a semicolon. 3: Repair the header if needed. A truncated dump may lack the final COMMIT; or, for mysqldump with --add-drop-table, may have an INSERT without its closing. Add COMMIT; if the dump used explicit transactions. 4: Import the prefix into a scratch database and count rows. You'll get every row committed before truncation; anything after the break is genuinely lost unless you have another copy.

Encoding damage is a separate failure. If file mydb.sql reports something other than ASCII/UTF-8, or imports throw "incorrect string value," convert with iconv -f LATIN1 -t UTF8 mydb.sql -o mydb_utf8.sql. If the file went through a Windows text-mode transfer and shows ^M at line ends, sed -i 's/\r$//' mydb.sql fixes it—but only after backing up the original.

A dump that imports cleanly but has wrong-looking data usually means the dump was taken with a different --default-character-set than the import connection; set both to utf8mb4 and retry from the original.

Repair a damaged server so you can export at all

When the server itself won't start, you can't dump, and the recovery is about the data directory, not a file. Start with the least invasive check: does the server start with recovery options?

For MySQL/InnoDB, innodb_force_recovery runs from 1 (skip some checks) to 6 (skip redo log rollback). Set it in my.cnf under [mysqld], start the server, and immediately mysqldump every database. Use the lowest value that lets the server start; higher values increase the chance of losing recent transactions. Do not run writes against a server in force-recovery mode. If it won't start even at 6, the data directory needs specialist attention.

For PostgreSQL, a server that won't start usually reports the failing relation in the log. pg_resetwal is a last resort that can discard WAL; it should only be run with a full backup of the data directory and after accepting possible data loss. Export with pg_dumpall as soon as the server is up.

The professional stop condition: if the data is business-critical and force-recovery doesn't produce a clean dump on the first or second attempt, stop and copy the entire data directory to separate storage before trying anything else. Repeated failed recovery attempts on InnoDB or PostgreSQL can make a specialist's job harder.

Verify the recovered file before you trust it

A file that exists is not a file that works. Three checks catch most silent recovery failures.

Structural check. For a MySQL dump, grep -c "CREATE TABLE" mydb.sql should match your table count, and the tail should contain -- Dump completed. For PostgreSQL, pg_restore --list mydb.dump lists every object without touching a database and fails loudly on a corrupt archive.

Count check. Import into a scratch database and compare SELECT COUNT(*) on the three largest tables against the source—or against a known-good earlier backup. Row counts alone don't prove content integrity, but a mismatch tells you recovery is incomplete.

Spot check. Pull a few recent rows you can identify by timestamp and confirm they're present. For a dump recovered after deletion, this is the only way to know whether you got the version you needed or an older one.

Practical limits and common mistakes

Deletion recovery on modern filesystems is unreliable by default. ext4's delayed allocation and btrfs's copy-on-write both reduce undelete success, and TRIM on SSDs can zero the blocks within minutes. If the file was on an SSD and the machine stayed on, plan for backup-based recovery instead. That's why the first rule is to stop writes immediately.

Do not run mysql < dump.sql against production "to see if it works." Dumps typically include DROP TABLE IF EXISTS, so a partial import can drop a live table and then fail before reloading it. Always restore to a scratch database first.

Do not edit a corrupted dump in place. Copy it first; a bad sed or head truncation is unrecoverable once saved over the original.

Do not attempt innodb_force_recovery levels above what's needed, and do not run recovery attempts on a failing disk. Both turn a recoverable problem into a permanent one.

Finally, the only recovery method that reliably works is a tested backup. If this incident was close, take a fresh dump, restore it into a scratch database, and confirm the counts—the moment you need a backup is the worst time to find out it was never restorable.