SQL ENCODE and DECODE (bytea)
encode(bytes, 'base64') turns a bytea into printable text and decode(text, 'base64') turns it back. Formats are hex, base64 and escape.
- Returns
text or bytea- In this category
- 20 of 39
语法
encode(bytea, format)
decode(text, format)
Each block is a separate form. The support table and the examples show which engine takes which.
引擎支持
| 引擎 | Support | 备注 |
|---|---|---|
| SQL Server | Not built in | CONVERT styles 1 and 2 for hex; BASE64_ENCODE/BASE64_DECODE on SQL Server 2025 |
| PostgreSQL | 是 | Supported under this name. |
| MySQL | Not built in | TO_BASE64/FROM_BASE64 and HEX/UNHEX cover the formats |
| SQLite | Not built in | hex() and unhex() (3.41+); base64() only in the sqlite3 shell |
| Oracle | Not built in | UTL_ENCODE and RAWTOHEX/HEXTORAW; Oracle's DECODE is a conditional |
示例
PostgreSQL
SELECT encode('SQL'::bytea, 'base64') AS b64;
PostgreSQL
SELECT decode('U1FM', 'base64') AS bytes;
PostgreSQL
SELECT convert_from(decode('53514C', 'hex'), 'UTF8') AS text_out;
值得了解
- Do not confuse this decode with Oracle's DECODE (a CASE-like conditional) or MySQL's old DECODE encryption function, removed in 8.0: this pair only changes how bytes are written as text.
- encode takes bytea and returns text; decode takes text and returns bytea. To encode a string, cast it first ('SQL'::bytea) or use convert_to(text, 'UTF8') to pick the encoding.
- The formats are hex, base64 and escape. PostgreSQL's base64 is the standard alphabet with = padding and a line break every 76 characters, so URL-safe tokens need translate() afterwards.
Questions about ENCODE / DECODE
Which PostgreSQL DECODE is which?
decode(text, format) converts hex/base64 text to bytea. Oracle's DECODE is a conditional expression. Same name, unrelated jobs: a recurring porting trap.
How do I decode into readable text?
Chain it: convert_from(decode(hex_text, 'hex'), 'UTF8'). decode alone stops at bytes; convert_from applies the character encoding.
Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.
Related on SQLly
- Custom sort order: CASE, FIELD and DECODE Dialect comparison
- NULL-safe equality: IS NOT DISTINCT FROM, <=> and IS Dialect comparison
- Compute MD5 or SHA-256 hashes of values in SQL Snippet
Cheat sheets for the engines that have it: PostgreSQL.
Functions your engine actually has
SQLly's completion lists the built-in functions of the engine you're connected to, whether that's SQL Server, PostgreSQL, MySQL, SQLite or Oracle. Hover a function for help, and signature hints show each argument as you type.