SHA2

更新时间:
复制 MD 格式

Computes the SHA-2 cryptographic hash of a STRING or BINARY expression and returns the result as a hexadecimal string.

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 STRING: the hexadecimal SHA-2 hash computed with the digest length specified by number.

Returns NULL if:

  • Either input parameter is null.

  • number is not a valid value (0, 224, 256, 384, 512).

Usage notes

  • SHA-2 is irreversible — you cannot recover the original input from the hash.

  • Setting number to 0 is equivalent to 256 and 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

Passing a null parameter returns NULL.

SELECT sha2('ABC', null);

Output:

+------+
| _c0  |
+------+
| NULL |
+------+

Example 3: Invalid number value

An invalid number (not 0, 224, 256, 384, or 512) returns NULL.

SELECT sha2('ABC', 100);

Output:

+------+
| _c0  |
+------+
| NULL |
+------+

Related functions

Other functions covers additional hash and encoding functions.