// strings reference

SQL SHA2 function

Returns the SHA-2 family hash of a string using the requested digest length.

カテゴリ
Strings
Returns
string
In this category
125 of 172

構文

SHA2(string, digest_length)
digest lengths: 224, 256, 384, 512 (0 = 256)

Each block is a separate form. The support table and the examples show which engine takes which.

エンジンサポート

エンジンSupportメモ
SQL Server Different name or syntax HASHBYTES('SHA2_256' or 'SHA2_512', value); no 224 or 384.
PostgreSQL Different name or syntax sha224(), sha256(), sha384() and sha512() are built in from PostgreSQL 11.
MySQL はい SHA2(str, n) is built in.
SQLite Not built in No SHA2 built in.
Oracle Different name or syntax STANDARD_HASH(value, 'SHA256'), also SHA384 and SHA512.

例

MySQL

SELECT SHA2('hello', 256) AS digest;

PostgreSQL

SELECT encode(sha256('hello'), 'hex') AS digest;

SQL Server

SELECT CONVERT(varchar(64), HASHBYTES('SHA2_256', 'hello'), 2) AS digest;

知っておくと便利なこと

  • MySQL's second argument must be 224, 256, 384, 512 or 0 (meaning 256). Any other value returns NULL rather than raising an error.
  • MySQL returns lowercase hex, twice the digest size in characters: 64 for SHA-256, 128 for SHA-512. PostgreSQL's sha256() returns bytea; wrap it in encode(..., 'hex').
  • SHA-2 is still fast, so it is not password storage on its own; use a slow salted function (bcrypt, scrypt, Argon2) in application code.

Questions about SHA2

What does the second argument of SHA2 mean?

The digest length in bits. SHA2(str, 256) is SHA-256; the choice changes both the output length and the collision resistance.

Is SHA2 suitable for password hashing?

Not alone. It is fast and unsalted, so GPU cracking wins. Use bcrypt, scrypt or Argon2 with a salt, computed outside the database.

How do I hash a file's contents in SQL?

Load the bytes as a binary or blob value and hash that: MySQL's SHA2 accepts binary strings, PostgreSQL's sha256 takes bytea, and SQL Server's HASHBYTES takes varbinary(max).

Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.

Cheat sheets for the engines that have it: SQL Server, PostgreSQL, MySQL, Oracle.

// fewer lookups

Functions your engine actually has

SQLly's completion lists the built-in functions of the engine you're connected to, whether that's SQL Server, PostgreSQL, MySQL, SQLite or Oracle. Hover a function for help, and signature hints show each argument as you type.