> For the complete documentation index, see [llms.txt](https://docs.postgresql.tw/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.postgresql.tw/the-sql-language/functions/functions-binarystring.md).

# 9.5. Binary String Functions and Operators \#

This section describes functions and operators for examining and manipulating binary strings, that is values of type `bytea`. Many of these are equivalent, in purpose and syntax, to the text-string functions described in the previous section.

SQL defines some string functions that use key words, rather than commas, to separate arguments. Details are in [Table 9.11](#FUNCTIONS-BINARYSTRING-SQL). PostgreSQL also provides versions of these functions that use the regular function invocation syntax (see [Table 9.12](#FUNCTIONS-BINARYSTRING-OTHER)).

**Table 9.11. SQL Binary String Functions and Operators**

| <p>Function/Operator</p><p>Description</p><p>Example(s)</p>                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           |                       |                                                                                                                                                                                                                                                                                                                                                                                                                                                                               |   |                                                                    |
| --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | - | ------------------------------------------------------------------ |
| <p><code>bytea</code> <code>                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          |                       | </code> <code>bytea</code> → <code>bytea</code></p><p>Concatenates the two binary strings.</p><p><code>'\x123456'::bytea                                                                                                                                                                                                                                                                                                                                                      |   | '\x789a00bcde'::bytea</code> → <code>\x123456789a00bcde</code></p> |
| <p><code>bit\_length</code> ( <code>bytea</code> ) → <code>integer</code></p><p>Returns number of bits in the binary string (8 times the <code>octet\_length</code>).</p><p><code>bit\_length('\x123456'::bytea)</code> → <code>24</code></p>                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         |                       |                                                                                                                                                                                                                                                                                                                                                                                                                                                                               |   |                                                                    |
| <p><code>btrim</code> ( <em><code>bytes</code></em> <code>bytea</code>, <em><code>bytesremoved</code></em> <code>bytea</code> ) → <code>bytea</code></p><p>Removes the longest string containing only bytes appearing in <em><code>bytesremoved</code></em> from the start and end of <em><code>bytes</code></em>.</p><p><code>btrim('\x1234567890'::bytea, '\x9012'::bytea)</code> → <code>\x345678</code></p>                                                                                                                                                                                                                                                                                                                                                       |                       |                                                                                                                                                                                                                                                                                                                                                                                                                                                                               |   |                                                                    |
| <p><code>ltrim</code> ( <em><code>bytes</code></em> <code>bytea</code>, <em><code>bytesremoved</code></em> <code>bytea</code> ) → <code>bytea</code></p><p>Removes the longest string containing only bytes appearing in <em><code>bytesremoved</code></em> from the start of <em><code>bytes</code></em>.</p><p><code>ltrim('\x1234567890'::bytea, '\x9012'::bytea)</code> → <code>\x34567890</code></p>                                                                                                                                                                                                                                                                                                                                                             |                       |                                                                                                                                                                                                                                                                                                                                                                                                                                                                               |   |                                                                    |
| <p><code>octet\_length</code> ( <code>bytea</code> ) → <code>integer</code></p><p>Returns number of bytes in the binary string.</p><p><code>octet\_length('\x123456'::bytea)</code> → <code>3</code></p>                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              |                       |                                                                                                                                                                                                                                                                                                                                                                                                                                                                               |   |                                                                    |
| <p><code>overlay</code> ( <em><code>bytes</code></em> <code>bytea</code> <code>PLACING</code> <em><code>newsubstring</code></em> <code>bytea</code> <code>FROM</code> <em><code>start</code></em> <code>integer</code> \[ <code>FOR</code> <em><code>count</code></em> <code>integer</code> ] ) → <code>bytea</code></p><p>Replaces the substring of <em><code>bytes</code></em> that starts at the <em><code>start</code></em>'th byte and extends for <em><code>count</code></em> bytes with <em><code>newsubstring</code></em>. If <em><code>count</code></em> is omitted, it defaults to the length of <em><code>newsubstring</code></em>.</p><p><code>overlay('\x1234567890'::bytea placing '\002\003'::bytea from 2 for 3)</code> → <code>\x12020390</code></p> |                       |                                                                                                                                                                                                                                                                                                                                                                                                                                                                               |   |                                                                    |
| <p><code>position</code> ( <em><code>substring</code></em> <code>bytea</code> <code>IN</code> <em><code>bytes</code></em> <code>bytea</code> ) → <code>integer</code></p><p>Returns first starting index of the specified <em><code>substring</code></em> within <em><code>bytes</code></em>, or zero if it's not present.</p><p><code>position('\x5678'::bytea in '\x1234567890'::bytea)</code> → <code>3</code></p>                                                                                                                                                                                                                                                                                                                                                 |                       |                                                                                                                                                                                                                                                                                                                                                                                                                                                                               |   |                                                                    |
| <p><code>rtrim</code> ( <em><code>bytes</code></em> <code>bytea</code>, <em><code>bytesremoved</code></em> <code>bytea</code> ) → <code>bytea</code></p><p>Removes the longest string containing only bytes appearing in <em><code>bytesremoved</code></em> from the end of <em><code>bytes</code></em>.</p><p><code>rtrim('\x1234567890'::bytea, '\x9012'::bytea)</code> → <code>\x12345678</code></p>                                                                                                                                                                                                                                                                                                                                                               |                       |                                                                                                                                                                                                                                                                                                                                                                                                                                                                               |   |                                                                    |
| <p><code>substring</code> ( <em><code>bytes</code></em> <code>bytea</code> \[ <code>FROM</code> <em><code>start</code></em> <code>integer</code> ] \[ <code>FOR</code> <em><code>count</code></em> <code>integer</code> ] ) → <code>bytea</code></p><p>Extracts the substring of <em><code>bytes</code></em> starting at the <em><code>start</code></em>'th byte if that is specified, and stopping after <em><code>count</code></em> bytes if that is specified. Provide at least one of <em><code>start</code></em> and <em><code>count</code></em>.</p><p><code>substring('\x1234567890'::bytea from 3 for 2)</code> → <code>\x5678</code></p>                                                                                                                     |                       |                                                                                                                                                                                                                                                                                                                                                                                                                                                                               |   |                                                                    |
| <p><code>trim</code> ( \[ <code>LEADING</code>                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        | <code>TRAILING</code> | <code>BOTH</code> ] <em><code>bytesremoved</code></em> <code>bytea</code> <code>FROM</code> <em><code>bytes</code></em> <code>bytea</code> ) → <code>bytea</code></p><p>Removes the longest string containing only bytes appearing in <em><code>bytesremoved</code></em> from the start, end, or both ends (<code>BOTH</code> is the default) of <em><code>bytes</code></em>.</p><p><code>trim('\x9012'::bytea from '\x1234567890'::bytea)</code> → <code>\x345678</code></p> |   |                                                                    |
| <p><code>trim</code> ( \[ <code>LEADING</code>                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        | <code>TRAILING</code> | <code>BOTH</code> ] \[ <code>FROM</code> ] <em><code>bytes</code></em> <code>bytea</code>, <em><code>bytesremoved</code></em> <code>bytea</code> ) → <code>bytea</code></p><p>This is a non-standard syntax for <code>trim()</code>.</p><p><code>trim(both from '\x1234567890'::bytea, '\x9012'::bytea)</code> → <code>\x345678</code></p>                                                                                                                                    |   |                                                                    |

<br>

Additional binary string manipulation functions are available and are listed in [Table 9.12](#FUNCTIONS-BINARYSTRING-OTHER). Some of them are used internally to implement the SQL-standard string functions listed in [Table 9.11](#FUNCTIONS-BINARYSTRING-SQL).

**Table 9.12. Other Binary String Functions**

| <p>Function</p><p>Description</p><p>Example(s)</p>                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         |
| ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| <p><code>bit\_count</code> ( <em><code>bytes</code></em> <code>bytea</code> ) → <code>bigint</code></p><p>Returns the number of bits set in the binary string (also known as “popcount”).</p><p><code>bit\_count('\x1234567890'::bytea)</code> → <code>15</code></p>                                                                                                                                                                                                                                                                                                                                                                                       |
| <p><code>crc32</code> ( <code>bytea</code> ) → <code>bigint</code></p><p>Computes the CRC-32 value of the binary string.</p><p><code>crc32('abc'::bytea)</code> → <code>891568578</code></p>                                                                                                                                                                                                                                                                                                                                                                                                                                                               |
| <p><code>crc32c</code> ( <code>bytea</code> ) → <code>bigint</code></p><p>Computes the CRC-32C value of the binary string.</p><p><code>crc32c('abc'::bytea)</code> → <code>910901175</code></p>                                                                                                                                                                                                                                                                                                                                                                                                                                                            |
| <p><code>get\_bit</code> ( <em><code>bytes</code></em> <code>bytea</code>, <em><code>n</code></em> <code>bigint</code> ) → <code>integer</code></p><p>Extracts <a href="#FUNCTIONS-ZEROBASED-NOTE">n'th</a> bit from binary string.</p><p><code>get\_bit('\x1234567890'::bytea, 30)</code> → <code>1</code></p>                                                                                                                                                                                                                                                                                                                                            |
| <p><code>get\_byte</code> ( <em><code>bytes</code></em> <code>bytea</code>, <em><code>n</code></em> <code>integer</code> ) → <code>integer</code></p><p>Extracts <a href="#FUNCTIONS-ZEROBASED-NOTE">n'th</a> byte from binary string.</p><p><code>get\_byte('\x1234567890'::bytea, 4)</code> → <code>144</code></p>                                                                                                                                                                                                                                                                                                                                       |
| <p><code>length</code> ( <code>bytea</code> ) → <code>integer</code></p><p>Returns the number of bytes in the binary string.</p><p><code>length('\x1234567890'::bytea)</code> → <code>5</code></p>                                                                                                                                                                                                                                                                                                                                                                                                                                                         |
| <p><code>length</code> ( <em><code>bytes</code></em> <code>bytea</code>, <em><code>encoding</code></em> <code>name</code> ) → <code>integer</code></p><p>Returns the number of characters in the binary string, assuming that it is text in the given <em><code>encoding</code></em>.</p><p><code>length('jose'::bytea, 'UTF8')</code> → <code>4</code></p>                                                                                                                                                                                                                                                                                                |
| <p><code>md5</code> ( <code>bytea</code> ) → <code>text</code></p><p>Computes the MD5 <a href="#FUNCTIONS-HASH-NOTE">hash</a> of the binary string, with the result written in hexadecimal.</p><p><code>md5('Th\000omas'::bytea)</code> → <code>8ab2d3c9689aaf18​b4958c334c82d8b1</code></p>                                                                                                                                                                                                                                                                                                                                                               |
| <p><code>reverse</code> ( <code>bytea</code> ) → <code>bytea</code></p><p>Reverses the order of the bytes in the binary string.</p><p><code>reverse('\xabcd'::bytea)</code> → <code>\xcdab</code></p>                                                                                                                                                                                                                                                                                                                                                                                                                                                      |
| <p><code>set\_bit</code> ( <em><code>bytes</code></em> <code>bytea</code>, <em><code>n</code></em> <code>bigint</code>, <em><code>newvalue</code></em> <code>integer</code> ) → <code>bytea</code></p><p>Sets <a href="#FUNCTIONS-ZEROBASED-NOTE">n'th</a> bit in binary string to <em><code>newvalue</code></em>.</p><p><code>set\_bit('\x1234567890'::bytea, 30, 0)</code> → <code>\x1234563890</code></p>                                                                                                                                                                                                                                               |
| <p><code>set\_byte</code> ( <em><code>bytes</code></em> <code>bytea</code>, <em><code>n</code></em> <code>integer</code>, <em><code>newvalue</code></em> <code>integer</code> ) → <code>bytea</code></p><p>Sets <a href="#FUNCTIONS-ZEROBASED-NOTE">n'th</a> byte in binary string to <em><code>newvalue</code></em>.</p><p><code>set\_byte('\x1234567890'::bytea, 4, 64)</code> → <code>\x1234567840</code></p>                                                                                                                                                                                                                                           |
| <p><code>sha224</code> ( <code>bytea</code> ) → <code>bytea</code></p><p>Computes the SHA-224 <a href="#FUNCTIONS-HASH-NOTE">hash</a> of the binary string.</p><p><code>sha224('abc'::bytea)</code> → <code>\x23097d223405d8228642a477bda2​55b32aadbce4bda0b3f7e36c9da7</code></p>                                                                                                                                                                                                                                                                                                                                                                         |
| <p><code>sha256</code> ( <code>bytea</code> ) → <code>bytea</code></p><p>Computes the SHA-256 <a href="#FUNCTIONS-HASH-NOTE">hash</a> of the binary string.</p><p><code>sha256('abc'::bytea)</code> → <code>\xba7816bf8f01cfea414140de5dae2223​b00361a396177a9cb410ff61f20015ad</code></p>                                                                                                                                                                                                                                                                                                                                                                 |
| <p><code>sha384</code> ( <code>bytea</code> ) → <code>bytea</code></p><p>Computes the SHA-384 <a href="#FUNCTIONS-HASH-NOTE">hash</a> of the binary string.</p><p><code>sha384('abc'::bytea)</code> → <code>\xcb00753f45a35e8bb5a03d699ac65007​272c32ab0eded1631a8b605a43ff5bed​8086072ba1e7cc2358baeca134c825a7</code></p>                                                                                                                                                                                                                                                                                                                                |
| <p><code>sha512</code> ( <code>bytea</code> ) → <code>bytea</code></p><p>Computes the SHA-512 <a href="#FUNCTIONS-HASH-NOTE">hash</a> of the binary string.</p><p><code>sha512('abc'::bytea)</code> → <code>\xddaf35a193617abacc417349ae204131​12e6fa4e89a97ea20a9eeee64b55d39a​2192992a274fc1a836ba3c23a3feebbd​454d4423643ce80e2a9ac94fa54ca49f</code></p>                                                                                                                                                                                                                                                                                               |
| <p><code>substr</code> ( <em><code>bytes</code></em> <code>bytea</code>, <em><code>start</code></em> <code>integer</code> \[, <em><code>count</code></em> <code>integer</code> ] ) → <code>bytea</code></p><p>Extracts the substring of <em><code>bytes</code></em> starting at the <em><code>start</code></em>'th byte, and extending for <em><code>count</code></em> bytes if that is specified. (Same as <code>substring(</code><em><code>bytes</code></em><code> from </code><em><code>start</code></em><code> for </code><em><code>count</code></em><code>)</code>.)</p><p><code>substr('\x1234567890'::bytea, 3, 2)</code> → <code>\x5678</code></p> |

<br>

Functions `get_byte` and `set_byte` number the first byte of a binary string as byte 0. Functions `get_bit` and `set_bit` number bits from the right within each byte; for example bit 0 is the least significant bit of the first byte, and bit 15 is the most significant bit of the second byte.

For historical reasons, the function `md5` returns a hex-encoded value of type `text` whereas the SHA-2 functions return type `bytea`. Use the functions [`encode`](#FUNCTION-ENCODE) and [`decode`](#FUNCTION-DECODE) to convert between the two. For example write `encode(sha256('abc'), 'hex')` to get a hex-encoded text representation, or `decode(md5('abc'), 'hex')` to get a `bytea` value.

Functions for converting strings between different character sets (encodings), and for representing arbitrary binary data in textual form, are shown in [Table 9.13](#FUNCTIONS-BINARYSTRING-CONVERSIONS). For these functions, an argument or result of type `text` is expressed in the database's default encoding, while arguments or results of type `bytea` are in an encoding named by another argument.

**Table 9.13. Text/Binary String Conversion Functions**

| <p>Function</p><p>Description</p><p>Example(s)</p>                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         |
| -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| <p><code>convert</code> ( <em><code>bytes</code></em> <code>bytea</code>, <em><code>src\_encoding</code></em> <code>name</code>, <em><code>dest\_encoding</code></em> <code>name</code> ) → <code>bytea</code></p><p>Converts a binary string representing text in encoding <em><code>src\_encoding</code></em> to a binary string in encoding <em><code>dest\_encoding</code></em> (see <a href="/pages/K3KyxIrYnTBgioozq3bL#MULTIBYTE-CONVERSIONS-SUPPORTED">Section 23.3.4</a> for available conversions).</p><p><code>convert('text\_in\_utf8', 'UTF8', 'LATIN1')</code> → <code>\x746578745f696e5f75746638</code></p> |
| <p><code>convert\_from</code> ( <em><code>bytes</code></em> <code>bytea</code>, <em><code>src\_encoding</code></em> <code>name</code> ) → <code>text</code></p><p>Converts a binary string representing text in encoding <em><code>src\_encoding</code></em> to <code>text</code> in the database encoding (see <a href="/pages/K3KyxIrYnTBgioozq3bL#MULTIBYTE-CONVERSIONS-SUPPORTED">Section 23.3.4</a> for available conversions).</p><p><code>convert\_from('text\_in\_utf8', 'UTF8')</code> → <code>text\_in\_utf8</code></p>                                                                                          |
| <p><code>convert\_to</code> ( <em><code>string</code></em> <code>text</code>, <em><code>dest\_encoding</code></em> <code>name</code> ) → <code>bytea</code></p><p>Converts a <code>text</code> string (in the database encoding) to a binary string encoded in encoding <em><code>dest\_encoding</code></em> (see <a href="/pages/K3KyxIrYnTBgioozq3bL#MULTIBYTE-CONVERSIONS-SUPPORTED">Section 23.3.4</a> for available conversions).</p><p><code>convert\_to('some\_text', 'UTF8')</code> → <code>\x736f6d655f74657874</code></p>                                                                                        |
| <p><code>encode</code> ( <em><code>bytes</code></em> <code>bytea</code>, <em><code>format</code></em> <code>text</code> ) → <code>text</code></p><p>Encodes binary data into a textual representation; supported <em><code>format</code></em> values are: <a href="#ENCODE-FORMAT-BASE64"><code>base64</code></a>, <a href="#ENCODE-FORMAT-ESCAPE"><code>escape</code></a>, <a href="#ENCODE-FORMAT-HEX"><code>hex</code></a>.</p><p><code>encode('123\000\001', 'base64')</code> → <code>MTIzAAE=</code></p>                                                                                                              |
| <p><code>decode</code> ( <em><code>string</code></em> <code>text</code>, <em><code>format</code></em> <code>text</code> ) → <code>bytea</code></p><p>Decodes binary data from a textual representation; supported <em><code>format</code></em> values are the same as for <code>encode</code>.</p><p><code>decode('MTIzAAE=', 'base64')</code> → <code>\x3132330001</code></p>                                                                                                                                                                                                                                             |

<br>

The `encode` and `decode` functions support the following textual formats:

base64[#](#ENCODE-FORMAT-BASE64) : The `base64` format is that of [RFC 2045 Section 6.8](https://datatracker.ietf.org/doc/html/rfc2045#section-6.8). As per the RFC, encoded lines are broken at 76 characters. However instead of the MIME CRLF end-of-line marker, only a newline is used for end-of-line. The `decode` function ignores carriage-return, newline, space, and tab characters. Otherwise, an error is raised when `decode` is supplied invalid base64 data — including when trailing padding is incorrect.

escape[#](#ENCODE-FORMAT-ESCAPE) : The `escape` format converts zero bytes and bytes with the high bit set into octal escape sequences (`\`*`nnn`*), and it doubles backslashes. Other byte values are represented literally. The `decode` function will raise an error if a backslash is not followed by either a second backslash or three octal digits; it accepts other byte values unchanged.

hex[#](#ENCODE-FORMAT-HEX) : The `hex` format represents each 4 bits of data as one hexadecimal digit, `0` through `f`, writing the higher-order digit of each byte first. The `encode` function outputs the `a`-`f` hex digits in lower case. Because the smallest unit of data is 8 bits, there are always an even number of characters returned by `encode`. The `decode` function accepts the `a`-`f` characters in either upper or lower case. An error is raised when `decode` is given invalid hex data — including when given an odd number of characters.

In addition, it is possible to cast integral values to and from type `bytea`. Casting an integer to `bytea` produces 2, 4, or 8 bytes, depending on the width of the integer type. The result is the two's complement representation of the integer, with the most significant byte first. Some examples:

```

1234::smallint::bytea          \x04d2
cast(1234 as bytea)            \x000004d2
cast(-1234 as bytea)           \xfffffb2e
'\x8000'::bytea::smallint      -32768
'\x8000'::bytea::integer       32768
```

Casting a `bytea` to an integer will raise an error if the length of the `bytea` exceeds the width of the integer type.

See also the aggregate function `string_agg` in [Section 9.21](/the-sql-language/functions/functions-aggregate.md) and the large object functions in [Section 33.4](/client-interfaces/largeobjects/lo-funcs.md).

***

原文：[PostgreSQL 18.6 Documentation](https://www.postgresql.org/docs/18/functions-binarystring.html)（英文原文，待翻譯）


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://docs.postgresql.tw/the-sql-language/functions/functions-binarystring.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
