CONVERT_TO

Encode a text string as BYTEA using a specified target character encoding.

Category: encodingReturns: BINARYDialect: PostgreSql

Syntax

CONVERT_TO(str, dest_encoding)

Description

## Overview Encodes a text string into the specified destination character encoding and returns the result as BYTEA. Use this when outbound data must be written in a legacy encoding, or when bytes are needed for hashing, signing, or transport over a binary channel. The function is the inverse of CONVERT_FROM. Characters that cannot be represented in the destination encoding raise an error rather than being silently substituted. ## Behavior - Returns NULL if either argument is NULL. - Raises an error if the input contains characters that are not representable in the destination encoding. - Encoding name is case-insensitive. - The output BYTEA length equals the byte length of the encoded form, which may differ from the input character count for multi-byte encodings. - Return type is BYTEA. ## Compatibility - Encoding names follow the iconv / PostgreSQL encoding catalog. - Output bytes are identical to what a native encoder for the target encoding would produce.

Parameters

NameTypeDescription
strSpecifies the text string to encode. Returns NULL for NULL input.
dest_encodingSpecifies the target character encoding for the output bytes. Accepts standard encoding names including 'UTF8', 'LATIN1', 'WIN1252', 'SQL_ASCII'. The encoding name is case-insensitive.

Examples

-- Encode text as UTF-8 bytes
SELECT CONVERT_TO('Hello', 'UTF8') AS bytes;
-- Encode as LATIN1
SELECT CONVERT_TO('Hello', 'LATIN1') AS bytes;
-- NULL input returns NULL
SELECT CONVERT_TO(NULL, 'UTF8') AS bytes;
-- Round-trip through LATIN1
SELECT CONVERT_FROM(CONVERT_TO('test string', 'LATIN1'), 'LATIN1') AS back;
-- Realistic: write a LATIN1 payload to a BYTEA column
SELECT CONVERT_TO(message_body, 'LATIN1') AS legacy_bytes
FROM messaging.outbound.pending
WHERE target_system = 'legacy-gateway';

Pitfalls

See Also

Open in interactive docs →   DeltaForge home →