Open In App

What is Collation and Character Set in MySQL?

MySQL Collation has always been a mystifying topic for beginners of  MySQL learners. A MySQL collation is a well-defined set of rules which are used to compare characters of a particular character-set by using their corresponding encoding. Each character set in MySQL might have more than one collation, and has, at least, one default collation. Two character sets cannot have the same collation.

SET NAMES 'utf8'; 

There is a MySQL statement to know about the default collations of character sets as follows:



SHOW CHARACTER SET;

                                                             

Char-set

                                                                    



Fetching char-set using LIKE statement

SHOW COLLATION LIKE 'character_set_name%';


                                                                                  

Fetching Collations using WHERE statement

1.  _cs(Case-sensitive) ,
2.  _bin(Binary) 
CREATE DATABASE name_of_database
CHARACTER SET character-set_name;
COLLATE collation_name;

Example:

CREATE DATABASE my_database
CHARACTER SET utf8mb4
COLLATE utf8_unicode_ci;

You can also change or apply character-set and collation-name for database using MySQL ‘ALTER’ statement :

ALTER DATABASE database_name
CHARACTER SET character_set_name
COLLATE collation_name; 

Example:

ALTER DATABASE my_database
CHARACTER SET utf8mb4
COLLATE  utf8mb4_0900_ai_ci;

MySQL query for Setting of character-set and collations at the table level: </b> You can also explicitly specify what type of character set and collation you want at the time of table creation, but If you don’t specify then default character-set and collation would be applied.

CREATE TABLE table_name(
ID   INT   AUTO_INCREMENT  NOT NULL,
NAME VARCHAR (20)     NOT NULL,
ADDRESS  CHAR (25) ,
SALARY   DECIMAL (18, 2),        
PRIMARY KEY (ID) );
CHARACTER SET character_set_name
COLLATE collation_name ;
ALTER TABLE table_name(
RENAME COLUMN old_name TO new_name);
CHARACTER SET character_set_name
COLLATE collation_name;
ALTER TABLE table_name
MODIFY column_name   VARCHAR(25)
CHARACTER SET latin1;
Article Tags :