encode And decode Convert bytea Text

Convert bytea values to hex and base64 with encode, parse them back with decode, and verify round trips and byte lengths.

SqlData Integrity

Code

snippet
CREATE TABLE attachments (
  id int PRIMARY KEY,
  payload bytea NOT NULL
);

INSERT INTO attachments (id, payload)
VALUES
  (1, decode('48656c6c6f', 'hex')),
  (2, decode('4465764578', 'hex')),
  (3, convert_to('café', 'UTF8'));

SELECT id,
       encode(payload, 'hex') AS hex_text,
       encode(payload, 'base64') AS base64_text,
       length(payload) AS byte_length
FROM attachments
ORDER BY id;

-- decode reverses encode for both formats.
SELECT encode(decode(encode(payload, 'base64'), 'base64'), 'hex')
       = encode(payload, 'hex') AS round_trip
FROM attachments;

-- escape keeps printable ASCII and escapes control bytes.
SELECT encode(
  convert_to('line 1' || chr(10) || 'line 2', 'UTF8'),
  'escape'
) AS escaped;

Inside the snippet

Several statements share this file — SELECT / INSERT / CREATE, with attachments among the objects involved.

Breaking the statements into their working parts: an ORDER BY that fixes the output order; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity.

Using it

Run the statement against the attachments table.

Key statements

SELECT id,
encode(payload, 'hex') AS hex_text,
encode(payload, 'base64') AS base64_text,
length(payload) AS byte_length
FROM attachments
ORDER BY id;
INSERT INTO attachments (id, payload)
VALUES
(1, decode('48656c6c6f', 'hex')),
(2, decode('4465764578', 'hex')),
(3, convert_to('café', 'UTF8'));
SELECT encode(decode(encode(payload, 'base64'), 'base64'), 'hex')
= encode(payload, 'hex') AS round_trip
FROM attachments;

Interactive Tools for This Topic

FAQ

Which tables appear in this script?
The references are `attachments`.