SQL HASHBYTES function
Computes a hash of a value in SQL Server using an algorithm you name, returning binary bytes.
- カテゴリ
- Strings
- Returns
varbinary- In this category
- 126 of 172
構文
HASHBYTES('algorithm', value)
algorithms: MD2, MD4, MD5, SHA, SHA1, SHA2_256, SHA2_512
Each block is a separate form. The support table and the examples show which engine takes which.
エンジンサポート
| エンジン | Support | メモ |
|---|---|---|
| SQL Server | はい | Supported under this name. |
| PostgreSQL | Different name or syntax | md5(), sha256() and friends, or pgcrypto's digest(). |
| MySQL | Different name or syntax | MD5, SHA1 or SHA2. |
| SQLite | Not built in | No built-in hashing. |
| Oracle | Different name or syntax | STANDARD_HASH(value, 'SHA256'). |
例
SQL Server
SELECT HASHBYTES('SHA2_256', 'hello') AS digest;
SQL Server
SELECT CONVERT(varchar(64), HASHBYTES('SHA2_256', email), 2) AS hex
FROM users;
知っておくと便利なこと
- An unsupported algorithm name such as 'SHA256' or 'SHA2_384' returns NULL, not an error, so a typo shows up as missing hashes rather than a failed query.
- varchar and nvarchar hash differently: 'hello' is 5 bytes, N'hello' is 10 bytes of UTF-16. Match the type and encoding of whatever system you compare against.
- The 8,000-byte input limit was removed in SQL Server 2016; older versions need chunking for larger values.
Questions about HASHBYTES
Why does HASHBYTES return weird characters?
It returns binary bytes, not text. Convert with style 2: CONVERT(varchar(64), digest, 2) gives a hex string without the 0x prefix.
What are the supported algorithms?
MD2, MD4, MD5, SHA, SHA1, SHA2_256 and SHA2_512. Since SQL Server 2016 everything except SHA2_256 and SHA2_512 is deprecated.
What is the MySQL equivalent?
MD5(str), SHA1(str) and SHA2(str, n) return lowercase hex text directly.
Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.
Related on SQLly
Cheat sheets for the engines that have it: SQL Server, PostgreSQL, MySQL, Oracle.
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.