Selective SQL Exports with WP-CLI

Sometimes you need to perform a selective SQL export of rows in a database table.

Recently, I found out that you can pass extra arguments to the mysqldump command through wp-cli. Taking a closer look at the wp-cli documentation shows that you can use --<field>=<value> to narrow your query.

For example, you can use the --where argument to only export posts that match a specific post type:

wp db export --tables=wp_posts --where='post_type = 'my_custom_post_type'

That command would give you an SQL file that you could then use to import into another site. I’ve used this a few times and it makes exports really quick. Even more so when you’re working with tables that have a couple hundred thousand rows.