The UNHEX function converts a hexadecimal string back to the original string, serving as the inverse operation of the HEX function. This function converts every two hexadecimal characters (0-9, A-F, a-f) into one byte. The UNHEX_NULL function works identically but returns NULL instead of an empty string when encountering invalid input. These functions are useful when handling binary data, encrypted data, or data requiring hexadecimal representation.
:::tip This function is supported since version 3.0.6. :::
UNHEX(<str>)
| Parameter | Description |
|---|---|
<str> | The hexadecimal character string |
Returns VARCHAR type, representing the decoded original string from hexadecimal.
Decoding rules:
Special cases (UNHEX):
Special cases (UNHEX_NULL):
select unhex('@');
+------------+ | unhex('@') | +------------+ | | +------------+
select unhex_null('@');
+-----------------+ | unhex_null('@') | +-----------------+ | NULL | +-----------------+
select unhex('41');
+-------------+ | unhex('41') | +-------------+ | A | +-------------+
select unhex('4142'), unhex('48656C6C6F');
+---------------+----------------------+ | unhex('4142') | unhex('48656C6C6F') | +---------------+----------------------+ | AB | Hello | +---------------+----------------------+
SELECT UNHEX(NULL), UNHEX_NULL(NULL);
+-------------+-----------------+ | UNHEX(NULL) | UNHEX_NULL(NULL) | +-------------+-----------------+ | | NULL | +-------------+-----------------+
SELECT UNHEX('E4B8AD'), UNHEX('E69687');
+-----------------+-----------------+ | UNHEX('E4B8AD') | UNHEX('E69687') | +-----------------+-----------------+ | 中 | 文 | +-----------------+-----------------+
SELECT UNHEX(HEX('Hello')), UNHEX(HEX('Test123'));
+---------------------+------------------------+ | UNHEX(HEX('Hello')) | UNHEX(HEX('Test123')) | +---------------------+------------------------+ | Hello | Test123 | +---------------------+------------------------+
UNHEX, UNHEX_NULL, HEX