Calculates the SHA-2 hash value of a STRING or BINARY expression.
Syntax
string sha2(string|binary <expr>, bigint <number>)Parameters
| Parameter | Required | Data type | Description |
|---|---|---|---|
| *expr* | Yes | STRING or BINARY | The expression to hash. |
| *number* | Yes | BIGINT | The SHA-2 variant to use, specified as a bit length. Valid values: 0, 224, 256, 384, 512. A value of 0 is equivalent to 256. |
Return value
Returns a value of STRING type containing the hexadecimal representation of the SHA-2 hash, computed using the digest length specified by number.
The function returns NULL in either of the following cases:
Any input parameter is null.
The
numbervalue is not one of the valid values (0,224,256,384,512).
Usage notes
SHA-2 is a one-way cryptographic hash function. You cannot reverse the hash to recover the original input.
Setting
numberto0is equivalent to256and produces a SHA-256 hash.
Examples
Example 1: Compute a SHA-256 hash
SELECT sha2('ABC', 256);Output:
+---------------------------------------------------------------------+
| _c0 |
+---------------------------------------------------------------------+
| b5d4045c3f466fa91fe2cc6abe79232a1a57cdf104f7a26e716e0a1e2789df78 |
+---------------------------------------------------------------------+Example 2: NULL input parameter
If either parameter is null, the function returns NULL.
SELECT sha2('ABC', null);Output:
+------+
| _c0 |
+------+
| NULL |
+------+Example 3: Invalid number value
If number is not a valid bit length (0, 224, 256, 384, 512), the function returns NULL.
SELECT sha2('ABC', 100);Output:
+------+
| _c0 |
+------+
| NULL |
+------+Related functions
For more hash and encoding functions, see Other functions.