MySQL interview question · Most asked
What is the difference between utf8 and utf8mb4 in MySQL, and why does it matter?
Summary
MySQL's old utf8 (an alias of utf8mb3) stores at most 3 bytes per character, so it cannot store emoji or some CJK characters; inserts fail or are truncated. utf8mb4 is real UTF-8 and is the default in MySQL 8.0, with the collation utf8mb4_0900_ai_ci.
Longer Answer
Use utf8mb4 for everything, including the connection character set (SET NAMES utf8mb4 or the driver option); a mismatch between connection and column charset leads to mojibake. Collations decide comparison and sorting: _ai_ci is accent- and case-insensitive (so 'resume' = 'résumé'), _as_cs is sensitive, _bin compares bytes. Unique indexes follow the collation, so case-insensitive collations make [email protected] and [email protected] duplicates. Joining columns with different collations can prevent index use.
Key Points
utf8= 3-byte utf8mb3; use utf8mb4.- Default in 8.0: utf8mb4_0900_ai_ci.
- Collation affects equality, sorting and uniqueness.
- Match connection charset.
More most-asked MySQL questions
- What is a clustered index in InnoDB, and why does primary key choice matter so much?
- Why is OFFSET pagination slow on large tables, and what is keyset pagination?
- How do you read EXPLAIN output in MySQL?
- Why might MySQL not use an index you created?
- What are the transaction isolation levels, and which does InnoDB use by default?
- How does a composite index work, and what is the leftmost-prefix rule?
- What causes deadlocks in MySQL, and how do you handle them?
- What are gap locks and next-key locks, and why do they surprise developers?