MySQL - Understanding the CREATE DATABASE command

·

3 min read

In the world of databases, creating a new database is the first step toward organizing and managing your data. In MySQL, the CREATE DATABASE command is the key to setting up a new database, and it comes with some powerful options that allow you to define how the database handles character encoding and sorting. Let's dive into these options: CHARACTER SET and COLLATE

The CHARACTER SET option

A character set, in simple terms, is a collection of characters with a defined encoding. It determines how the individual characters are stored in the database, allowing MySQL to understand and handle different languages, symbols, and special characters. The CHARACTER SET option in the CREATE DATABASE command lets you specify which character set the new database should use.

Suppose that we have an alphabet with four letters: A, B, a, b. We give each letter a number: A = 0, B = 1, a = 2, b = 3. The letter A is a symbol, the number 0 is the encoding for A, and the combination of all four letters and their encodings is a CHARACTER SET.

SHOW CHARACTER SET;

SHOW CHARACTER SET LIKE 'utf%';

The COLLATE option

Collation goes hand in hand with the character set. While the character set defines the encoding of characters, collation defines the rules for comparing and sorting these characters. It determines the order in which characters appear when you perform sorting or comparison operations in the database.

Suppose that we want to compare two string values, A and B. The simplest way to do this is to look at the encodings: 0 for A and 1 for B. Because 0 is less than 1, we say A is less than B. What we've just done is apply a collation to our character set. The collation is a set of rules (only one rule in this case): “compare the encodings.” We call this simplest of all possible collations a binary collation.

But what if we want to say that the lowercase and uppercase letters are equivalent? Then we would have at least two rules: (1) treat the lowercase letters a and b as equivalent to A and B; (2) then compare the encodings. We call this a case-insensitive collation. It is a little more complex than a binary collation.

SHOW COLLATION WHERE Charset = 'utf8mb4';

SUMMARY

In real life, most character sets have many characters: not just A and B but whole alphabets, sometimes multiple alphabets or eastern writing systems with thousands of characters, along with many special symbols and punctuation marks. Also in real life, most collations have many rules, not just for whether to distinguish lettercase, but also for whether to distinguish accents (an “accent” is a mark attached to a character as in German Ö), and for multiple-character mappings (such as the rule that Ö = OE in one of the two German collations).

CREATE DATABASE Merch_Store DEFAULT CHARACTER SET utf8mb4 DEFAULT COLLATE utf8mb4_unicode_ci;