In MySQL, CHARSET()
is a built in function that returns the character set of its string argument.
We provide the string when we call the function.
Syntax
The syntax goes like this:
CHARSET(str)
Where str
is the string for which we want the character set of.
Example
Here’s a simple example:
SELECT CHARSET('Coffee');
Result:
+-------------------+ | CHARSET('Coffee') | +-------------------+ | utf8mb4 | +-------------------+
And here it is again after we convert the same string to utf16:
SELECT CHARSET(CONVERT('Coffee' USING utf16));
Result:
+----------------------------------------+ | CHARSET(CONVERT('Coffee' USING utf16)) | +----------------------------------------+ | utf16 | +----------------------------------------+
And here’s another example that uses Thai characters:
SELECT CHARSET(_tis620'ไม้เมือง');
Result:
+--------------------------------------------+ | CHARSET(_tis620'ไม้เมือง') | +--------------------------------------------+ | tis620 | +--------------------------------------------+
Wrong Argument Type
Passing an argument that is not a string results in the word binary
being returned.
SELECT CHARSET(45);
Result:
+-------------+ | CHARSET(45) | +-------------+ | binary | +-------------+
Null Arguments
Passing null
results in the word binary
being returned.
SELECT CHARSET(null);
Result:
+---------------+ | CHARSET(null) | +---------------+ | binary | +---------------+
Missing Argument
Calling CHARSET()
without passing an argument results in an error:
SELECT CHARSET();
Result:
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ')' at line 1