Convert an integer or string to its hexadecimal text representation.
HEX(expr)
## Overview Converts the input value to a hexadecimal text representation. For INTEGER inputs the numeric value is written in base 16 using uppercase letters A-F. For STRING inputs each byte of the UTF-8 encoding is written as a two-character hex pair, producing a stable byte-level view of the string. Use HEX for debugging, for rendering hashes or signatures as inspectable text, or as an alternative to BASE64 when a purely hex representation is required. ## Behavior - Returns NULL for NULL input. - Integer output is in base 16 with uppercase digits (no leading zeros, no '0x' prefix). - String output is two hex characters per UTF-8 byte, uppercase. - Zero is rendered as '0' (single character), not '00'. - Negative integers use two's-complement representation of a 64-bit form. - Output is a STRING. ## Algorithm - RFC 4648 Section 8 (Base16) alphabet, uppercase variant. - Output length for strings: 2 * byte-length of UTF-8 form. ## Compatibility - Alphabet matches RFC 4648 Base16 with uppercase digits. - Most SQL dialects expose an equivalent HEX function with the same conventions, but some use lowercase output; if round-tripping across systems, normalize case with UPPER() or LOWER().
| Name | Type | Description |
|---|---|---|
expr | Specifies the value to convert. For INTEGER inputs the numeric value is rendered as base-16. For STRING inputs each UTF-8 byte is rendered as a two-character hex pair. Returns NULL for NULL input. |
-- Integer to hex
SELECT HEX(255) AS h; -- 'FF'
-- Zero is rendered as '0'
SELECT HEX(0) AS h; -- '0'
-- String to hex byte pairs
SELECT HEX('ABC') AS h; -- '414243'
-- Round-trip with UNHEX
SELECT UNHEX(HEX(255)) AS b;
-- Realistic: render hashes for logging
SELECT event_id, HEX(hash_bytes) AS hash_hex
FROM security.audit.signed_events
WHERE created_date = DATE '2026-04-19';