Sub topic 14
Binary data with bytea
This chapter assumes you can create tables and run queries in psql, and that you know what text is and what a CHECK constraint does. It covers bytea, PostgreSQL's type for raw bytes: how values are written and displayed, which functions work on them, and when to store files in the database at all.
What bytea is
bytea ("byte array") holds a variable-length sequence of bytes. It differs from text in four ways:
- It has no character encoding. Any byte value from 0 to 255 is allowed, including the zero byte, which
textrejects. - Comparison is byte by byte. Collation does not apply.
- Length is measured in bytes.
octet_lengthandlengthreturn the same number forbytea. - It accepts no type modifier. There is no
bytea(n), so enforce a size cap with aCHECKconstraint.
Typical uses are hashes, small images, encrypted payloads, serialized protocol messages, and keys or tokens that are not text.
Writing and reading bytea values
PostgreSQL has two textual formats for bytea: hex and escape. Hex is the default for output and the one you should use for input. A hex literal starts with \x followed by two hex digits per byte.
SELECT '\xDEADBEEF'::bytea AS from_hex,
octet_length('\xDEADBEEF'::bytea) AS n_bytes,
encode('abc'::bytea, 'hex') AS abc_as_hex;The first column prints as \xdeadbeef, and n_bytes is 4. abc_as_hex is 616263. The output format is controlled by the bytea_output setting (hex or escape). Leave it on hex.
The backslash in '\xDEADBEEF' stays a literal backslash only when standard_conforming_strings is on. It is on by default in all supported versions.
Converting between text and bytea
A text value has no bytes until you pick an encoding. Use convert_to and convert_from for that, not a cast.
SELECT convert_to('café', 'UTF8') AS bytes,
octet_length(convert_to('café', 'UTF8')) AS n_bytes,
char_length('café') AS n_chars,
convert_from('\x636166c3a9'::bytea, 'UTF8') AS back_to_text;The result is \x636166c3a9, 5 bytes, 4 characters, and café. The letter é takes two bytes (c3 a9) in UTF-8.
'abc'::bytea works, but it does not encode the text. It parses the string as bytea input syntax, and that syntax treats backslashes as special.
SELECT 'a\b'::bytea;
-- ERROR: invalid input syntax for type bytea
SELECT convert_to('a\b', 'UTF8');
-- \x615c62For binary data that is not text, use encode and decode to move between bytea and a printable representation. The formats are hex, base64 and escape.
SELECT encode('hello'::bytea, 'base64') AS b64,
decode('aGVsbG8=', 'base64') AS raw,
encode('\x68656c6c6f'::bytea, 'hex') AS hex_text;This returns aGVsbG8=, \x68656c6c6f, and 68656c6c6f.
Working with bytes
The common functions and operators:
| Function or operator | What it does | Column | Column |
|---|---|---|---|
| `octet_length(b)` | Number of bytes | ||
| `b1 \ | \ | b2` | Concatenates two `bytea` values |
| `substring(b from 1 for 4)` | Extracts a range of bytes (1-based) | ||
| `get_byte(b, n)` / `set_byte(b, n, v)` | Reads or replaces one byte (0-based) | ||
| `position(sub in b)` | Finds a byte sequence | ||
| `sha256(b)`, `sha512(b)` | Returns the digest as `bytea` | ||
| `md5(b)` | Returns the digest as a hex `text` value |
Note the indexing difference: substring counts from 1, while get_byte counts from 0.
A common use is checking a file's signature. PNG files begin with the bytes 89 50 4E 47.
SELECT substring('\x89504e470d0a1a0a'::bytea from 1 for 4) = '\x89504e47'::bytea AS looks_like_png;A table that stores binary content
This table stores small attachments. It derives the size and hash from the content and caps the size.
CREATE TABLE attachments (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
filename text NOT NULL,
content bytea NOT NULL,
size_bytes integer GENERATED ALWAYS AS (octet_length(content)) STORED,
sha256 bytea GENERATED ALWAYS AS (sha256(content)) STORED,
CONSTRAINT content_max_1mb CHECK (octet_length(content) <= 1048576)
);
CREATE UNIQUE INDEX attachments_sha256_key ON attachments (sha256);
INSERT INTO attachments (filename, content)
VALUES ('hello.txt', '\x68656c6c6f');
SELECT filename, size_bytes, encode(sha256, 'hex') AS digest
FROM attachments;The query returns hello.txt, 5, and 2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824. Generated columns need PostgreSQL 12 or later.
The unique index sits on the 32-byte digest, not on content. A B-tree index entry has to fit roughly a third of an 8 kB page, so a large bytea value cannot be indexed directly. Indexing a hash gives you fast exact lookup and deduplication.
How bytea is stored
PostgreSQL stores large column values through TOAST (The Oversized-Attribute Storage Technique). When a row grows past about 2 kB, PostgreSQL compresses the large values and, if that is not enough, moves them to a separate TOAST table. The main table row keeps only a pointer.
This has three consequences:
- A single
byteavalue can be at most 1 GB, but practical limits are much lower. The client receives and sends the whole value, and both server and client hold it in memory. SELECT *on a table with largebyteacolumns fetches every value. List the columns you need instead.- Updating a row that has a large
byteavalue writes a new copy of that value when the column itself changes. Updating other columns of the row leaves the TOASTed data in place.
Already-compressed data such as JPEG, PNG, ZIP and encrypted payloads gains nothing from TOAST compression. You can skip the compression attempt with ALTER TABLE attachments ALTER COLUMN content SET STORAGE EXTERNAL;.
Choosing where binary data lives
| Option | Strengths | Weaknesses |
|---|---|---|
| `bytea` column | Transactional, backed up with the rest of the data, simple SQL | Whole value moves at once, 1 GB hard limit, bloats table backups |
| Large objects (`lo_*`) | Up to 4 TB, streaming reads and writes | Separate API, not deleted with the row unless you clean them up, awkward permissions |
| External storage plus a path or key | Cheap, scales, CDN friendly | Not transactional with your rows, can drift out of sync |
Keeping small files (avatars, thumbnails, signed documents) in bytea makes backups and consistency easy. For anything that grows into the tens of megabytes, store the file elsewhere and keep its key and sha256 in the table.
Common errors
- Using a cast for text.
'text'::byteare-parses the string asbyteainput and fails or misreads backslashes. Useconvert_to. - Building literals by hand in application code. Pass the bytes as a bound parameter through your driver, so it uses binary or hex encoding for you. Do not concatenate hex strings into SQL.
- Comparing
md5(bytea)with abyteadigest.md5returns text.sha256returnsbytea. Convert withencode(..., 'hex')ordecode(..., 'hex')before comparing. - Expecting
lengthto count characters. Forbyteait counts bytes. - Indexing the content column. Large values fail with an index row size error. Index a digest instead.
Exercise
You need to store a 40-byte API token that is random binary data, and look up rows by token. Write the column type, a constraint that enforces the exact length, and say why a plain '...'::bytea cast is a poor way to turn a text passphrase into bytes.
Show answer
Use token bytea NOT NULL CHECK (octet_length(token) = 40) with a unique B-tree index on token, which is small enough to index directly. A text value has no bytes until an encoding is chosen, and the ::bytea cast parses the string as bytea input syntax, so a backslash can cause an error or change the bytes. convert_to(passphrase, 'UTF8') makes the encoding explicit.
Exercise
What does get_byte('\x4a4b4c'::bytea, 1) return, and why is substring('\x4a4b4c'::bytea from 1 for 1) a different byte?
Show answer
It returns 75, the byte 4b in decimal. get_byte counts from 0, so position 1 is the second byte. substring counts from 1, so from 1 for 1 returns the first byte, \x4a.