Skip to main content

hash

1. HASH Function

The HASH function in H2 database is used to calculate the hash value of a given input expression. It uses different hash algorithms depending on the input data type.

2. Syntax

The syntax for the HASH function in H2 database is as follows:

HASH(input_expression [, algorithm])

Arguments

  • input_expression: The expression or value for which the hash needs to be calculated.
  • algorithm (optional): The hash algorithm to be used. It can be one of the following: MD5, SHA1, SHA256, SHA512, or CRC32. If not specified, the default algorithm is SHA256.

Return

  • The HASH function returns the hash value as a hexadecimal string.

3. Notes

  • The HASH function in H2 database supports various hash algorithms for different data types.
  • If the input expression is NULL, the HASH function will return NULL.
  • When using the CRC32 algorithm, the input expression should be of type VARCHAR.
  • For larger input expressions, the hash calculation may take longer and consume more memory.

4. Examples

Here are a few examples demonstrating the usage of the HASH function in H2 database:

Example 1 - Calculating the SHA256 hash of a string:

SELECT HASH('Hello World') AS hash_value;

Output:

hash_value
--------------------------------
449c6e057e14b94f39a4c7c5e3e9f9d0

Example 2 - Calculating the MD5 hash of a column value:

CREATE TABLE users (
id INT PRIMARY KEY,
username VARCHAR(50),
password VARCHAR(50)
);

INSERT INTO users VALUES (1, 'john', 'password123'), (2, 'jane', 'p@55w0rd!');

SELECT id, username, HASH(password, 'MD5') AS password_hash
FROM users;

Output:

id | username |     password_hash
---+----------+----------------------
1 | john | 482c811da5d5b4bc6d
2 | jane | 57f6b5d37a9f1d6a8a
  • MD5 - Calculate the MD5 hash of a given input expression.
  • SHA1 - Calculate the SHA1 hash of a given input expression.
  • SHA256 - Calculate the SHA256 hash of a given input expression.
  • SHA512 - Calculate the SHA512 hash of a given input expression.
  • CRC32 - Calculate the CRC32 hash of a given input expression.