SQL base64 encoding
Turns bytes into base64 text for embedding and transport. The bytes come from an encoding, and MySQL wraps lines; both facts surprise people.
- Category
- Strings
- Returns
string- In this category
- 56 of 172
Syntax
TO_BASE64(string)
encode(data, 'base64')
Each block is a separate form. The support table and the examples show which engine takes which.
Engine support
| Engine | Support | Notes |
|---|---|---|
| SQL Server | Not built in | No built-in equivalent. |
| PostgreSQL | Different name or syntax | encode(convert_to(s, 'utf8'), 'base64') |
| MySQL | Yes | Supported under this name. |
| SQLite | Not built in | No built-in equivalent. |
| Oracle | Not built in | No built-in equivalent. |
Examples
MySQL
SELECT TO_BASE64('ab') AS b64; -- YWI=
PostgreSQL
SELECT encode(convert_to('ab', 'utf8'), 'base64') AS b64; -- YWI=
Good to know
- MySQL's TO_BASE64 inserts a newline every 76 characters, MIME-style. Strip it with REPLACE for single-line output.
- PostgreSQL encodes bytea: encode(convert_to('héllo', 'utf8'), 'base64'). Encoding text directly needs that conversion step.
- The base64 payload reflects the source encoding: UTF-8 versus latin1 input gives different output for accented text.
- SQL Server and Oracle have no native function: SQL Server reaches for XML/FOR XML tricks, Oracle for UTL_ENCODE or APEX helpers.
Questions about TO_BASE64 / encode
Why does my base64 output contain newlines?
MySQL's TO_BASE64 wraps at 76 characters like MIME. REPLACE(TO_BASE64(x), '\n', '') produces the single-line form most consumers expect.
Does base64 encoding change my data?
Not the underlying bytes: the output is a reversible text form. It does grow size by about a third, and it is not encryption.
How do I base64 in SQL Server?
No built-in. The common tricks encode via FOR XML PATH and XQUERY, or you encode in the application layer before the value reaches SQL.
Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.
Related on SQLly
Cheat sheets for the engines that have it: PostgreSQL, MySQL.
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.