SQL Standard

SQL sha256

Hashing is one of the most common and basic forms of string. When storing sensitive data on a database, it is good to ensure that it’s stored in a secure method in case there are data breaches.

Although most applications will perform hashing on the backend before sending the data in the database, it can be beneficial to learn how to do it within the database engine.

In this article, we will explore how we can compute the hash of an input string using the SHA256 algorithm in Standard SQL.

Standard SQL SHA256 Function

The function provides a relatively simple syntax that allows you to compute the sha256 hash of a given string.

The syntax is as shown below:

SHA256(input)

The function accepts the input as a string type or a sequence of bytes. If you provide a string type, the function will treat it as an array of bytes before performing the hashing operation.

Practical Example

The example below shows how you can use the sha256 function to calculate the sha256 hash of the given string.

SELECT
  sha256("hello world") AS hash_value;

The code above will take the input string and return its equivalent sha256 hash. An example output is as shown:

hash_value
uU0nuZNNPgilLlLX2n2r+sSE7+N6U4DukIj3rOLvzek=

Keep in mind that the operation is irreversible. Hence, there is no function to convert a sha256 hash back to its original string.

Example 2

We can also provide a byte string as shown in the example below:

\
SELECT
  sha256(b"hello world") AS hash_value;

Similarly, the function will return the same hash value as shown:

hash_value
uU0nuZNNPgilLlLX2n2r+sSE7+N6U4DukIj3rOLvzek=

SHA512

Another function that may be beneficial to know is the sha512 function. It is similar to sha256 except it returns the hash of a given string using the SHA-512 algorithm.

The function syntax is as shown:

SHA512(input)

Example:

SELECT
  sha512(b"hello world") AS hash_value;

Output:

hash_value
MJ7MSJwS1utMxA9QyQLytNDtd+5RGnx6m808qG1M2G+YndNbxf9JlnDaNCVbRbDP2DDoH2Bdz33FVC6TrpzXbw==

You will notice that the resulting hash is different despite a similar input string. This is because the hashing algorithm is different and more complex.

Closing

In this article, we explored how we can hash an input string using SHA-256 and SHA-512 algorithms.

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