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.
Code
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
PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.ASCII Table ReferenceLook up any ASCII code point 0-127 by decimal, hex, or character and see the binary, octal, and control-name view.ASCII85 EncoderEncode and decode ASCII85 (Base85), the Adobe variant with z zero-compression, handling arbitrary bytes and Unicode.
FAQ
- Which tables appear in this script?
- The references are `attachments`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.