// strings reference

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.

Catégorie
Strings
Returns
binary
In this category
54 of 172

Syntaxe

UNHEX(hex_string)

Prise en charge des moteurs

MoteurSupportNotes
SQL Server Not built in No built-in equivalent.
PostgreSQL Different name or syntax decode(h, 'hex') returns bytea
MySQL Oui Supported under this name.
SQLite Oui unhex() from SQLite 3.41; returns a blob
Oracle Different name or syntax HEXTORAW returns RAW

Exemples

MySQL

SELECT UNHEX('6162') AS s;  -- ab

PostgreSQL

SELECT convert_from(decode('6162', 'hex'), 'utf8') AS s;  -- ab

Bon à savoir

  • 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.

Cheat sheets for the engines that have it: PostgreSQL, MySQL, SQLite, Oracle.

// fewer lookups

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.