// strings reference

SQL SHA1 function

Returns the 160-bit SHA-1 hash of a string as a 40-character hex digest.

Categoria
Strings
Returns
string
In this category
124 of 172

Sintaxe

SHA1(string)
SHA(string)
HASHBYTES('SHA1', value)

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

Suporte a mecanismos

MotorSupportNotas
SQL Server Different name or syntax HASHBYTES('SHA1', value), deprecated since SQL Server 2016.
PostgreSQL Different name or syntax No built-in SHA-1; digest(value, 'sha1') from pgcrypto.
MySQL Sim SHA1 and its alias SHA are built in.
SQLite Not built in No SHA1 built in.
Oracle Different name or syntax STANDARD_HASH(value, 'SHA1').

Exemplos

MySQL

SELECT SHA1('hello') AS digest;  -- aaf4c61ddcc5e8a2dabede0f3b482cd9aea9434d

PostgreSQL

SELECT encode(digest('hello', 'sha1'), 'hex') AS digest;  -- needs pgcrypto

Bom saber

  • SHA-1 collisions have been demonstrated since 2017, so it is retired for signatures and certificates. For non-adversarial checksums it still works where compatibility requires it.
  • MySQL returns 40 lowercase hex characters; SQL Server's HASHBYTES and Oracle's STANDARD_HASH return 20 raw bytes that need CONVERT(..., 2) or RAWTOHEX to display.
  • For new work prefer SHA-256: MySQL's SHA2(str, 256), PostgreSQL's sha256(), HASHBYTES('SHA2_256', v) and STANDARD_HASH(v, 'SHA256').

Questions about SHA1

Is SHA1 the same as SHA-1?

Yes. MySQL names the function SHA1 and also accepts SHA; the algorithm is the 160-bit SHA-1 standard.

Should I use SHA1 or SHA2 for new code?

SHA-2, usually SHA-256. SHA-1 collisions are practical, so anything security-adjacent should move.

How do I get SHA1 in PostgreSQL?

With pgcrypto: CREATE EXTENSION pgcrypto; then encode(digest(value, 'sha1'), 'hex'). PostgreSQL 11+ has sha224, sha256, sha384 and sha512 built in, but not SHA-1.

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.