CHAR() Examples in MySQL

In MySQL, the CHAR() function returns the character for each integer passed. In other words, you can pass in one or more integers, and the function will interpret those as code values for string characters and return the corresponding string for each code value.

Syntax

The syntax goes like this:

CHAR(N,... [USING charset_name])

Where N,... is one or more integers, and USING charset_name is an optional argument that you can use to specify the character set to use.

Example 1 – Basic Usage

Here’s an example to demonstrate the basic usage:

SELECT CHAR(67, 97, 116);

Result:

+-------------------+
| CHAR(67, 97, 116) |
+-------------------+
| Cat               |
+-------------------+

So if we change one of the integers, we get a different string:

SELECT CHAR(66, 97, 116);

Result:

+-------------------+
| CHAR(66, 97, 116) |
+-------------------+
| Bat               |
+-------------------+

Example 2 – The USING Clause

Here’s an example of adding the USING clause to specify UTF-8 encoding:

SELECT CHAR(0xc2a9 USING utf8);

Result:

+-------------------------+
| CHAR(0xc2a9 USING utf8) |
+-------------------------+
| ©                       |
+-------------------------+

And here’s another example where I specify the unicode code point:

SELECT CHAR(0x027FE USING ucs2);

Result:

+--------------------------+
| CHAR(0x027FE USING ucs2) |
+--------------------------+
| ⟾                        |
+--------------------------+

Example 3 – Multiple Result Bytes

Arguments larger than 255 are converted into multiple result bytes. Here’s an example to demonstrate.

SELECT 
  HEX(CHAR(1,0)), 
  HEX(CHAR(256)),
  HEX(CHAR(1,1)), 
  HEX(CHAR(257));

Result:

+----------------+----------------+----------------+----------------+
| HEX(CHAR(1,0)) | HEX(CHAR(256)) | HEX(CHAR(1,1)) | HEX(CHAR(257)) |
+----------------+----------------+----------------+----------------+
| 0100           | 0100           | 0101           | 0101           |
+----------------+----------------+----------------+----------------+

And if we increase the numbers:

SELECT 
  HEX(CHAR(7,0)), 
  HEX(CHAR(1792)),
  HEX(CHAR(7,7)), 
  HEX(CHAR(1799));

Result:

+----------------+-----------------+----------------+-----------------+
| HEX(CHAR(7,0)) | HEX(CHAR(1792)) | HEX(CHAR(7,7)) | HEX(CHAR(1799)) |
+----------------+-----------------+----------------+-----------------+
| 0700           | 0700            | 0707           | 0707            |
+----------------+-----------------+----------------+-----------------+