MySQL Dump Table from query condition

You can add a where clause in your sqldump command

In order to test a project locally I needed access to the production website database. Unfortunately copying billions of records to my small development VM was not an option. I needed only the latest records but doing a sqldump would get me data from as far back as 2004. The cool thing however is that mysql allows you to add a condition on your mysqldump command to extract whatever you see fit. Let's break it down.

MySQLDump command

By default mysqldump command will make a copy of whatever database you pass it.

$> mysqldump -umy_user_name -p database_name > database_dump.sql

This will include the database schema and all the current data. This is usually what you are looking for. But when you only need the schema, the same command can do the trick with this flag:

$> mysqldump --no-data -umy_user_name -p database_name > database_dump.sql

The --no-data flag, as the name implies, will limit the dump to the schema only and no data.

MySQLDump a table

If you don't want a copy of the whole database, you have the options to dump specific tables. For that you only need to name the table list after the database name.

$> mysqldump -umy_user_name -p database_name  my_table1 > mytable1_dump.sql

Note that you can pass multiple tables if you like:

$> mysqldump -umy_user_name -p database_name  my_table1 my_table2  my_table3 > mytables_dump.sql

If you want only the schema of the tables you can pass the --no-data flag as usual or simply -d.

MySQLDump a table with a condition (--where)

This is the problem I was having. I didn't want to dump a billion records. I only wanted the records for this year and luckily mysqldump has a flag for that. So let's say I want to dump from my_table1 where the field date_created is greater than '2016-01-01'. Here is how I would write it.

$> mysqldump -umy_user_name -p database_name  --tables my_table1 --where="date_created > '2016-01-01' " > mytable1_filtered_dump.sql

I used the --tables flag to let mysql know that everything I pass after is a table name, then the --where flag allows me to pass a string for the condition. Note that the condition can be as complex as you want. All it cares about is that it is syntactically correct.

How do I figure out all I can do with mysqldump.

If you are reading this on my blog, it means you skipped the very first step you should have followed before googling. There is a in-depth documentation you can read before you google. And that documentation is available at your fingertips... no internet needed.

$> man mysqldump

The default manual contains all the information I have just told you and then some. Sometimes reading a little bit from it can go a long way. In the meanwhile enjoy exporting your database with a condition.


There are no comments added yet.

Let's hear your thoughts

For my eyes only