{"id":10,"date":"2008-12-08T08:44:24","date_gmt":"2008-12-08T06:44:24","guid":{"rendered":"http:\/\/code.openark.org\/blog\/?p=10"},"modified":"2008-12-16T09:58:14","modified_gmt":"2008-12-16T07:58:14","slug":"mysqls-character-sets-and-collations-demystified","status":"publish","type":"post","link":"https:\/\/code.openark.org\/blog\/mysql\/mysqls-character-sets-and-collations-demystified","title":{"rendered":"MySQL&#8217;s character sets and collations demystified"},"content":{"rendered":"<p>MySQL&#8217;s character sets and collations are often considered as a mystery, and many users either completely disregard them and keep with the defaults, or set everything to UTF8.<\/p>\n<p>This post will attempt to shed some light on the mystery, and provide with some best practices for use with text columns with regard to character sets.<!--more--><\/p>\n<h4>Character Sets<\/h4>\n<p>A thorough discussion of how the character sets have evolved through history is beyond the scope of this post. While the Unicode standard is gaining recognition, the &#8220;older&#8221; character sets are still around. Understanding the difference between Unicode and local character sets is crucial.<\/p>\n<p>Consider, for example, MySQL&#8217;s <strong><code>latin1<\/code><\/strong> character set. In this character set there are 256 different characters, represented by one byte. The first 128 characters map to ASCII, the standard &#8220;ABCabc012 dot comma&#8221; set, of which most of this post is composed. The latter 128 characters in <strong><code>latin1<\/code><\/strong> are composed of West European specific characters, such as \u00c0, \u00eb, \u00f5, \u00d1.<\/p>\n<p>A <strong><code>Name VARCHAR(60) CHARSET latin1<\/code><\/strong> column can describe names with West European characters. But it cannot describe Russian or Hebrew names. To represent a name in Hebrew, you&#8217;d need the <strong><code>hebrew<\/code><\/strong> charset (ISO 8859-8), in which the first 128 characters are, as always, mapped to ASCII, and the latter 128 characters describe the Hebrew alphabet and punctuation marks, such as \u05e9,\u05dc,\u05de,\u05d4. The Cyrillic, Arabic and Turkish charsets follow in a similar manner.<\/p>\n<p>Assume now I&#8217;m building a world wide web application, such as a popular social network. I would like to store the first names of my users, in every possible language. None of the above character sets support all languages. I therefore turn to <a title=\"What is Unicode\" href=\"http:\/\/www.unicode.org\/standard\/WhatIsUnicode.html\">Unicode<\/a>. In particular, MySQL supports <strong><code>utf8<\/code><\/strong>, a Unicode encoding scheme, which is commonly used due to its economic storage requirements.<\/p>\n<p>In Unicode there is a dedicated number for each letter in the known languages, in ancient languages, and some imaginary or otherwise non existing languages, such as Klingon (yes, I know there are people who actually speak Klingon), may yet find their way into the standard.<\/p>\n<p>UTF8 (or utf8), a Unicode encoding scheme, states the following: for ASCII characters, such as &#8216;a&#8217;, &#8216;6&#8217;, &#8216;$&#8217;, only one byte of storage is required. For Hebrew, Cyrillic or Turkish characters, 2 bytes are required. For Japanese, Chinese &#8211; more (MySQL supports up to 3 bytes per character). Again, the exact details of the implementation are beyond the scope of this post, and are well described <a title=\"UTF-8 and Unicode FAQ\" href=\"http:\/\/www.cl.cam.ac.uk\/~mgk25\/unicode.html#utf-8\">here<\/a> and <a title=\"Wikipedia - UTF-8\" href=\"http:\/\/en.wikipedia.org\/wiki\/UTF-8\">here.<\/a><\/p>\n<p>What&#8217;s important to me is that I can define <strong><code>Name VARCHAR(30) CHARSET utf8<\/code><\/strong> for my columns, and Voila! Any name can be represented in my database.<\/p>\n<h4>So why not define everything as utf8 and get done with it?<\/h4>\n<p>Well, it just so happens that Unicode comes with a price. See, for example, the following column definition:<strong><\/strong><\/p>\n<blockquote><p><code>CountryCode CHAR(3) CHARSET utf8<\/code><\/p><\/blockquote>\n<p>We are asking for a column with 3 characters exactly. The required storage for this column will be such that any 3-letter name must fit in. This means (3 characters) times (3 bytes per character) = 9 bytes of storage. So <strong><code>CHAR<\/code><\/strong> and <strong><code>utf8<\/code><\/strong> together may be less than ideal.<strong><code> VARCHAR<\/code><\/strong> behaves better: it only requires as many bytes per character as described above. So the text &#8220;abc&#8221; will only require 3 bytes (plus <strong><code>VARCHAR<\/code><\/strong>&#8216;s leading 1 or 2 bytes).<\/p>\n<h4>Why don&#8217;t we drop the &#8216;CHAR&#8217; altogether, then, and use only &#8216;VARCHAR&#8217;?<\/h4>\n<p>Because some values are simply better represented with <strong><code>CHAR<\/code><\/strong>: consider a &#8220;password&#8221; column, encoded with MD5. The <strong><code>MD5()<\/code><\/strong> function returns a 32 characters long text. It&#8217;s always 32 characters, and, moreover, it&#8217;s always in ASCII. The best data type and character set definition would be <strong><code>password CHAR(32) CHARSET ascii<\/code><\/strong>. We thus ensure exactly 32 bytes are allocated to this column. A <strong><code>VARCHAR<\/code><\/strong> will acquire an additional byte or two, depending on its defined length, which will indicate the length of the text.<\/p>\n<h4>And why would I care about collations?<\/h4>\n<p>Collations deal with text comparison. We observed that the default character set in MySQL is <strong><code>latin1<\/code><\/strong>. The default collation is <strong><code>latin1_swedish_ci<\/code><\/strong>. In this collation the following holds true: <strong><code>'ABC' = 'abc'<\/code><\/strong>.<\/p>\n<p>Wait. What?<\/p>\n<p>Look at the &#8220;ci&#8221; in <strong><code>latin1_swedish_ci<\/code><\/strong>. It stands for &#8220;case insensitive&#8221;. Collations which end with &#8220;cs&#8221; or &#8220;bin&#8221; are case sensitive. The <strong><code>utf8<\/code><\/strong> character set comes with <strong><code>utf8_general_ci<\/code><\/strong> collation. This can make sense. Let&#8217;s review our web application table (I&#8217;m using plain text passwords here, bare with me for this example):<\/p>\n<blockquote>\n<pre>CREATE TABLE my_users (\r\n  name VARCHAR(30) CHARSET utf8 COLLATE utf8_general_ci,\r\n  plainPassword VARCHAR(16) CHARSET ASCII,\r\n  UNIQUE KEY (name)\r\n);\r\nINSERT INTO my_users (name, password) VALUES ('David', 'mypass');<\/pre>\n<\/blockquote>\n<p>It holds true that the name &#8216;David&#8217; equals &#8216;david&#8217;. If I were to <strong><code>SELECT * FROM my_users WHERE name='david'<\/code><\/strong>, I would find the desired row. The unique key will also guarantee that no daVID user can be added.<\/p>\n<p>But David certainly wouldn&#8217;t want users to login with the password &#8216;MYPASS&#8217;. So we refine our table:<\/p>\n<blockquote>\n<pre>CREATE TABLE my_users (\r\n  name VARCHAR(30) CHARSET utf8 COLLATE utf8_general_ci,\r\n  plainPassword VARCHAR(16) CHARSET ascii COLLATE ascii_bin,\r\n  UNIQUE KEY (name)\r\n);<\/pre>\n<\/blockquote>\n<p>The <strong><code>ascii_bin<\/code><\/strong> collation is a case sensitive collation for <strong><code>ascii<\/code><\/strong>. The following will not find anything:<\/p>\n<blockquote><p><code>SELECT * FROM my_users WHERE name='david' AND plainPassword='MYPASS';<\/code><\/p><\/blockquote>\n<p>Holding a plain text password in your database is not a best practice, but apparently it&#8217;s common.<\/p>\n<p>Collations also deal with text ordering. For any two strings, the collation determines which is larger, or if they are equal. Probably the most common situation you see collations in action is when you <strong>ORDER BY<\/strong> a text column.<\/p>\n<h4>Also keep in mind<\/h4>\n<ul>\n<li>When you check for length of strings, do you use the <strong><code>LENGTH()<\/code><\/strong> function, as in <strong><code>SELECT LENGTH(Name) FROM City<\/code><\/strong>? You probably wish to replace this with <strong><code>CHAR_LENGTH()<\/code><\/strong>. <strong><code>LENGTH()<\/code><\/strong> returns the number of bytes required for the text storage. <strong><code>CHAR_LENGTH()<\/code><\/strong> returns the number of characters in the text, and is usually what you are looking for. It may hold true that for a string s, <strong><code>LENGTH(s)=12<\/code><\/strong> and <strong><code>CHAR_LENGTH(s)=8<\/code><\/strong>. Watch out for these glitches.<\/li>\n<li>You can converts texts between character sets with <strong><code>CONVERT<\/code><\/strong>. For example: <strong><code>CONVERT(s USING utf8)<\/code><\/strong><\/li>\n<li>Stored routines should not be overlooked. If your stored routine accepts a text argument, or if your stored function returns one, make sure the character sets are properly defined. If not, then your utf8 text may be converted to latin1 during the call to your stored routine. This also applies to local parameters within the stored routines.<\/li>\n<li>An <strong><code>ALTER TABLE <em>&lt;some table&gt;<\/em> CONVERT TO <em>&lt;some charset&gt;<\/em><\/code><\/strong> will change the character set not only for the table itself, but also for all existing textual columns.<\/li>\n<\/ul>\n<p>See the following post: <a title=\"Useful database analysis queries with INFORMATION_SCHEMA\" href=\"http:\/\/code.openark.org\/blog\/mysql\/useful-database-analysis-queries-with-information_schema\">Useful database analysis queries with INFORMATION_SCHEMA<\/a> for queries which diagnose your databases character sets.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>MySQL&#8217;s character sets and collations are often considered as a mystery, and many users either completely disregard them and keep with the defaults, or set everything to UTF8.<\/p>\n<p>This post will attempt to shed some light on the mystery, and provide with some best practices for use with text columns with regard to character sets.<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"jetpack_post_was_ever_published":false,"_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":false,"_jetpack_newsletter_tier_id":0,"_jetpack_memberships_contains_paywalled_content":false,"_jetpack_memberships_contains_paid_content":false,"footnotes":"","jetpack_publicize_message":"","jetpack_publicize_feature_enabled":true,"jetpack_social_post_already_shared":false,"jetpack_social_options":{"image_generator_settings":{"template":"highway","default_image_id":0,"enabled":false},"version":2}},"categories":[5],"tags":[18,21,20],"class_list":["post-10","post","type-post","status-publish","format-standard","hentry","category-mysql","tag-data-types","tag-sql","tag-syntax"],"jetpack_publicize_connections":[],"jetpack_featured_media_url":"","jetpack_sharing_enabled":true,"jetpack_shortlink":"https:\/\/wp.me\/p2bZZp-a","_links":{"self":[{"href":"https:\/\/code.openark.org\/blog\/wp-json\/wp\/v2\/posts\/10","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/code.openark.org\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/code.openark.org\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/code.openark.org\/blog\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/code.openark.org\/blog\/wp-json\/wp\/v2\/comments?post=10"}],"version-history":[{"count":24,"href":"https:\/\/code.openark.org\/blog\/wp-json\/wp\/v2\/posts\/10\/revisions"}],"predecessor-version":[{"id":395,"href":"https:\/\/code.openark.org\/blog\/wp-json\/wp\/v2\/posts\/10\/revisions\/395"}],"wp:attachment":[{"href":"https:\/\/code.openark.org\/blog\/wp-json\/wp\/v2\/media?parent=10"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/code.openark.org\/blog\/wp-json\/wp\/v2\/categories?post=10"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/code.openark.org\/blog\/wp-json\/wp\/v2\/tags?post=10"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}