SQL HEX function
Renders a value's bytes as hexadecimal text. The bytes come from the storage encoding, which is the entire gotcha.
- 类别
- Strings
- Returns
string- In this category
- 53 of 172
语法
HEX(string)
hex(blob)
encode(data, 'hex')
Each block is a separate form. The support table and the examples show which engine takes which.
引擎支持
| 引擎 | Support | 备注 |
|---|---|---|
| SQL Server | Different name or syntax | no HEX; CONVERT(varchar(max), CAST(s AS varbinary(max)), 2) renders the bytes |
| PostgreSQL | Different name or syntax | to_hex() for integers; encode(convert_to(...), 'hex') for text |
| MySQL | 是 | Supported under this name. |
| SQLite | 是 | Supported under this name. |
| Oracle | Different name or syntax | RAWTOHEX works on RAW-typed bytes |
示例
MySQL
SELECT HEX('ab') AS h; -- 6162
SQLite
SELECT hex('ab') AS h; -- 6162
PostgreSQL
SELECT encode(convert_to('ab', 'utf8'), 'hex') AS h; -- 6162
值得了解
- The output encodes the stored bytes: HEX('é') is C3A9 under utf8mb4 and E9 under latin1. Two engines, one string, two answers.
- Case differs by engine: MySQL HEX, SQLite hex() and Oracle RAWTOHEX return uppercase, PostgreSQL's encode() and to_hex() lowercase. Normalize before comparing hex strings.
- PostgreSQL splits the job: to_hex(n) formats integers, encode(bytea, 'hex') encodes bytes; convert_to turns text into bytea first.
- SQL Server has no HEX function: CONVERT(VARBINARY, s) displays 0x-prefixed bytes, and CONVERT(VARCHAR, bin, 2) renders them as plain hex.
Questions about HEX
Why is my hex string different on another server?
The stored bytes differ: a different charset or column type encodes the same text differently. HEX shows storage bytes, not abstract characters.
How do I decode hex back to text?
UNHEX('6162') on MySQL, CAST(unhex('6162') AS TEXT) on SQLite 3.41+, convert_from(decode('6162', 'hex'), 'utf8') on PostgreSQL, HEXTORAW on Oracle.
Does HEX work on numbers?
MySQL's HEX(255) is FF; it converts the number's value. SQLite's hex(255) is 323535, the bytes of the text '255'. Know which one your engine does.
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: SQL Server, 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.