The mysqldump
command is used to create logical backups of MySQL databases, allowing you to capture the structure and/or data for later restoration. One useful option is --order-by-primary
, which arranges rows in the output sorted by the primary key of the table. This can be beneficial when you want predictable ordering or when restoring data into another database system.
Here are several examples demonstrating the usage of --order-by-primary
in mysqldump
:
Example 1: Dumping a single table with rows ordered by primary key:
mysqldump --order-by-primary my_database my_table
This command dumps the my_table
from my_database
with rows ordered by the primary key.
Example 2: Dumping multiple tables with primary key ordering:
mysqldump --order-by-primary my_database table1 table2 table3
Here, mysqldump
dumps table1
, table2
, and table3
from my_database
with rows sorted by their respective primary keys.
Example 3: Dumping all databases with primary key ordering:
mysqldump --order-by-primary --all-databases
This command dumps all databases on the MySQL server with rows ordered by primary key.
Example 4: Redirecting output to a file:
mysqldump --order-by-primary my_database my_table > my_table_dump.sql
It dumps my_table
with primary key ordering into my_table_dump.sql
.
Example 5: Compressing the output:
mysqldump --order-by-primary my_database my_table | gzip > my_table_dump.sql.gz
This command dumps and compresses the output with primary key ordering into my_table_dump.sql.gz
.
Example 6: Verifying the dump:
head my_table_dump.sql
Use head
command to check the beginning of my_table_dump.sql
to ensure the primary key ordering is reflected.
Example 7: Checking specific data:
grep "INSERT INTO" my_table_dump.sql
Search for “INSERT INTO” statements in my_table_dump.sql
to confirm the ordering of data entries.
Example 8: Restoring data with primary key order:
mysql my_database < my_table_dump.sql
This command restores my_table_dump.sql
into my_database
while maintaining primary key ordering.
Example 9: Handling large databases:
mysqldump --order-by-primary --single-transaction --quick --routines my_database > my_database_dump.sql
It dumps my_database
with primary key ordering, using options to ensure a consistent and fast dump process.
Example 10: Dumping and excluding specific tables:
mysqldump --order-by-primary --ignore-table=my_database.table_to_ignore my_database > my_database_dump.sql
This command excludes table_to_ignore
from the dump while maintaining primary key order for other tables in my_database
.
Also check similar articles.
Enabling Optimization Options in mysqldump
Skipping SET NAMES Statement in mysqldump Output
Not Including Data Rows in mysqldump Output
Omitting Table Creation Info in mysqldump Output
Suppressing CREATE DATABASE Statements in mysqldump
Discussion about this post