← Tất cả bài viết

MySQL COLLATE Keyword

mysql

In MySQL, the COLLATE keyword is used to specify the collation of a string. A collation defines how string comparison is performed and how strings are sorted. It determines the rules for character comparison based on specific criteria, such as case sensitivity and accent sensitivity.


Key Aspects of COLLATE:

  • Sorting Order: The collation defines how strings are ordered. For example, “apple” and “Apple” might be considered the same in a case-insensitive collation but different in a case-sensitive collation.
  • Character Set: Collations are associated with character sets. Each character set can have multiple collations. For example, the utf8mb4 character set has collations like utf8mb4_general_ci (case-insensitive) and utf8mb4_bin (binary comparison).
  • Use in Table/Column Definitions: You can specify a collation when creating a table or column. For example:
CREATE TABLE my_table (
           my_column VARCHAR(255) COLLATE utf8mb4_unicode_ci
       );
  • Use in String Comparisons: You can use the COLLATE keyword in queries to specify how strings should be compared.
SELECT * FROM my_table WHERE my_column = 'example' COLLATE utf8mb4_general_ci;
  • Changing Collation: You can change the collation of an existing column using the ALTER TABLE statement.
ALTER TABLE my_table MODIFY my_column VARCHAR(255) COLLATE utf8mb4_bin;

Examples of Common Collations:

  • Case-insensitive:
    • utf8_general_ci: Case-insensitive comparison for the utf8 character set.
    • utf8mb4_unicode_ci: Case-insensitive comparison for the utf8mb4 character set, taking into account linguistic rules.
  • Case-sensitive:
    • utf8_bin: Binary comparison for the utf8 character set.
    • utf8mb4_bin: Binary comparison for the utf8mb4 character set.

Summary

The COLLATE keyword in MySQL allows you to control how string comparisons are performed, impacting sorting and searching operations. Choosing the appropriate collation is important for ensuring that string data behaves as expected in your database applications.