SQL UNHEX function
Decodes a hexadecimal string into binary data. Getting text back out needs one more cast, because the result is bytes, not characters.
- 類別
- Strings
- Returns
binary- In this category
- 54 of 172
語法
UNHEX(hex_string)
引擎支援
| 引擎 | Support | 備註 |
|---|---|---|
| SQL Server | Not built in | No built-in equivalent. |
| PostgreSQL | Different name or syntax | decode(h, 'hex') returns bytea |
| MySQL | 是 | Supported under this name. |
| SQLite | 是 | unhex() from SQLite 3.41; returns a blob |
| Oracle | Different name or syntax | HEXTORAW returns RAW |
範例
MySQL
SELECT UNHEX('6162') AS s; -- ab
PostgreSQL
SELECT convert_from(decode('6162', 'hex'), 'utf8') AS s; -- ab
小知識
- The result is binary: UNHEX('6162') is 'ab' only because the bytes are valid ASCII. Comparing it to text needs an explicit cast on most engines.
- Bad input is handled differently: MySQL and SQLite return NULL for non-hex characters, PostgreSQL's decode() raises an error, Oracle's HEXTORAW raises ORA-01465.
- PostgreSQL's bytea result needs convert_from(decode(...), 'utf8') to become text.
- SQL Server has no UNHEX: CONVERT(varbinary(max), '6162', 2) parses hex text without the 0x prefix (style 1 expects it).
Questions about UNHEX
Why does UNHEX return gibberish or NULL?
Either the hex encodes bytes that are not valid text in the session charset, or the input was not valid hex; MySQL returns NULL for that case instead of erroring.
What is the PostgreSQL equivalent of UNHEX?
decode(hex, 'hex'), which returns bytea. Wrap it in convert_from(..., 'utf8') when the target is text.
Does UNHEX work on odd-length input?
MySQL pads a leading zero, so UNHEX('616') is the two bytes 0x06 0x16, probably not what you meant. Fix the length in the source rather than relying on it.
Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.
Related on SQLly
Cheat sheets for the engines that have it: PostgreSQL, MySQL, SQLite, Oracle.
Functions your engine actually has
SQLly's completion lists the built-in functions of the engine you're connected to, whether that's SQL Server, PostgreSQL, MySQL, SQLite or Oracle. Hover a function for help, and signature hints show each argument as you type.