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:
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.
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:
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:
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:
Example:
sha512(b"hello world") AS hash_value;
Output:
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.