In this article, we will discuss how we can convert a string to and from Base64 string in Standard SQL.
Standard SQL Convert String to Base64
In Standard SQL, we can use the TO_BASE64 method to convert an input string into a base64 string.
The function syntax is as shown:
The function will take the input string as bytes and convert it into Base64 encoding.
Let us look at a practical example of how we can convert a string to Base64 using this function.
An example is as shown below:
to_base64(b'welcome to standard sql');
The code above will take the input byte sequence and convert it into a base64 string. An example output is as shown:
d2VsY29tZSB0byBzdGFuZGFyZCBzcWw=
You can rename the output column to something readable as:
to_base64(b'welcome to standard sql') AS b64_string;
Output string:
d2VsY29tZSB0byBzdGFuZGFyZCBzcWw=
Standard SQL Convert Base64 to String
Similarly, if you have a base64 encoded string and you wish to convert it back into a string, you can use the from_base64 function.
The function syntax is as shown:
The function will take the input base64 string and decode it into bytes.
An example is as shown:
from_base64('d2VsY29tZSB0byBzdGFuZGFyZCBzcWw=') AS bytes;
The code should return:
d2VsY29tZSB0byBzdGFuZGFyZCBzcWw=
Keep in mind that the from_base64 function will return the decoded string as bytes displayed as b64 encoded string.
Conclusion
In this article, you learned how to convert a string to and from base64 encoding format.