The character encoding of a MySQL database determines how text data is stored and interpreted. Using the correct encoding is important for proper display of special characters, diacritics, and multilingual content.
Before making any changes, it is strongly recommended to create a full database backup.
Table of Contents
Changing the database encoding
To change the character set of an existing database, you can use the ALTER DATABASE command.
Example:
ALTER DATABASE database_name
CHARACTER SET utf8mb4
COLLATE utf8mb4_unicode_ci;
Where:
database_name– the name of the databaseutf8mb4– the character set to be usedutf8mb4_unicode_ci– the collation associated with the selected character set
The utf8mb4 character set is generally recommended because it supports the full range of Unicode characters.
Important considerations
Changing the default encoding of a database does not automatically convert the encoding of existing tables and columns.
In some cases, additional commands may be required to update:
- existing tables
- column definitions
- imported data
Failure to perform a complete conversion may result in incorrectly displayed characters.
Creating a backup before changes
Before modifying the encoding, create a backup of your database:
mysqldump -u username -p database_name > backup.sql
This allows you to restore your data if any issues occur during the conversion process.
Importing data with a specific encoding
When restoring a database, you can specify the character set during import:
mysql -u username -p --default-character-set=utf8mb4 database_name < backup.sql
Replace:
usernamewith your MySQL userdatabase_namewith the target database name
Best practices
Before changing the encoding:
- create a complete backup
- verify the current database encoding
- check the encoding of tables and columns
- test the conversion on a development copy if possible
This helps prevent data corruption and character display issues.
Summary
You can change a MySQL database’s default encoding using the ALTER DATABASE command. Before making any changes, create a backup and verify that tables and columns are also configured correctly. For most modern applications, the utf8mb4 character set is the recommended choice.