How to take backup of a single table in a MySQL database?

Viewed 677519

By default, mysqldump takes the backup of an entire database. I need to backup a single table in MySQL. Is it possible? How do I restore it?

10 Answers

just use mysqldump -u root database table or if using with password mysqldump -u root -p pass database table

I've come across this and wanted to extend others' answers with our fully working example:

This will backup the schema in it's own file, then each database table in its own file.

The date format means you can run this as often as your hard drive space allows.


DATE=`date '+%Y-%m-%d-%H'`
BACKUP_DIR=backups/
DATABASE_NAME=database_name
mysqldump --column-statistics=0  --user=fake --password=secure --host=10.0.0.1  --routines --triggers --single-transaction --no-data --databases ${DATABASE_NAME} | gzip > ${BACKUP_DIR}${DATE}-${DATABASE_NAME}--schema.sql.gz
for table in $(mysql  --user=fake --password=secure --host=10.0.0.1 -AN -e "SHOW TABLES FROM ${DATABASE_NAME};");
    do
    echo ""
    echo ""
    echo "mysqldump --column-statistics=0  --user=fake --password=secure --host=10.0.0.1 --routines --triggers --single-transaction --databases ${DATABASE_NAME} --tables ${table} | gzip > ${BACKUP_DIR}${DATE}-${DATABASE_NAME}-${table}.sql.gz"
    mysqldump --column-statistics=0  --user=fake --password=secure --host=10.0.0.1 --routines --triggers --single-transaction --databases ${DATABASE_NAME} --tables ${table} | gzip > ${BACKUP_DIR}${DATE}-${DATABASE_NAME}-${table}.sql.gz
done

We run this as bash script on an hourly basis, and actually have HOUR checks and only backup some tables through the day, then all tables in the night.

to keep some space on the drives, the script also runs this to remove backups older than X days.

# HOW MANY DAYS SHOULD WE KEEP
DAYS_TO_KEEP=25
DAYSAGO=$(date --date="${DAYS_TO_KEEP} days ago" +"%Y-%m-%d-%H")
echo $DAYSAGO
rm -Rf ${BACKUP_DIR}${DAYSAGO}-*
echo "rm -Rf ${BACKUP_DIR}${DAYSAGO}-*"

Related