SQL Standard

Standard SQL to and from base64

Base64 is one of the most common methods of encoding data. It is a quick and easy reversible method of data encoding used in a wide range of situations.

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:

TO_BASE64(bytes_expr)

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:

SELECT

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:

f0_

d2VsY29tZSB0byBzdGFuZGFyZCBzcWw=

You can rename the output column to something readable as:

SELECT

to_base64(b'welcome to standard sql') AS b64_string;

Output string:

b64_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:

FROM_BASE64(string_expr)

The function will take the input base64 string and decode it into bytes.

An example is as shown:

SELECT

from_base64('d2VsY29tZSB0byBzdGFuZGFyZCBzcWw=') AS bytes;

The code should return:

bytes

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.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list