MySQL Tutorial MySQL Advanced MySQL Database Account Management MySQL References

MySQL TO_BASE64() Function



The MySQL TO_BASE64() function converts the specified string to base-64 encoded form and returns the result as a character string with the connection character set and collation. If the argument is not a string, it is converted to a string before conversion takes place. The result is NULL if the argument is NULL. Base-64 encoded strings can be decoded using the FROM_BASE64() function.

Different base-64 encoding schemes exist. These are the encoding and decoding rules used by TO_BASE64() and FROM_BASE64():

  • The encoding for alphabet value 62 is '+'.
  • The encoding for alphabet value 63 is '/'.
  • Encoding output is made up of groups of four printable characters, with each three bytes of data encoded using four characters. If the final group is not complete, it is padded with '=' characters to make up a length of four.
  • To divide long output, a newline is added after every 76 characters.
  • Decoding recognizes and ignores newline, carriage return, tab, and space.

Syntax

TO_BASE64(string)

Parameters

string Required. Specify the string to encode.

Return Value

Returns the encoded data, as a string.

Example 1:

The example below shows the usage of TO_BASE64() function.

mysql> SELECT TO_BASE64('Hello');
Result: 'SGVsbG8='

mysql> SELECT FROM_BASE64(TO_BASE64('Hello'));
Result: 'Hello'

mysql> SELECT FROM_BASE64('SGVsbG8=');
Result: 'Hello'

Example 2:

Consider a database table called Sample with the following records:

DataName
Data 1John
Data 2Marry
Data 3Jo
Data 4Kim
Data 5Ramesh

The statement given below can be used to encode the records of column Name to base-64.

SELECT *, TO_BASE64(Name) AS TO_BASE64_Value FROM Sample;

This will produce the result as shown below:

DataNameTO_BASE64_Value
Data 1JohnSm9obg==
Data 2MarryTWFycnk=
Data 3JoSm8=
Data 4KimS2lt
Data 5RameshUmFtZXNo

❮ MySQL Functions