// SQL snippet

Compute MD5 or SHA-256 hashes of values in SQL

You need a stable fingerprint of an email or a row payload for dedupe keys and change detection.

Main statement
MySQL
También cubre
SQL Server PostgreSQL Oracle

The task

A hash gives you a short, stable, non-reversible fingerprint. MySQL's MD5 and SHA2 are the simplest one-call options.

The snippet

Written for MySQL. Versions for SQL Server, PostgreSQL and Oracle are under Variations.

MySQL
SELECT
    MD5(email) AS email_md5,
    SHA2(CONCAT(customer_id, ':', email), 256) AS row_sha256
FROM users;

Cómo funciona

MD5 returns a 32-character lowercase hex digest; SHA2(value, 256) returns 64 characters. Concatenating the primary key with the value fingerprints the row, and the separator stops 'ab'+'c' colliding with 'a'+'bc'. MD5 is fine for dedupe keys but must not be treated as security. Hashes only match across engines when the input bytes match: on SQL Server, HASHBYTES of an NVARCHAR value hashes UTF-16 bytes and gives a different digest from the same text as VARCHAR.

Variations

PostgreSQL 11+

PostgreSQL
SELECT
    MD5(email) AS email_md5,
    encode(sha256(convert_to(CONCAT(customer_id, ':', email), 'UTF8')), 'hex') AS row_sha256
FROM users;

SQL Server

SQL Server
SELECT
    LOWER(CONVERT(VARCHAR(32), HASHBYTES('MD5', email), 2)) AS email_md5,
    LOWER(CONVERT(VARCHAR(64), HASHBYTES('SHA2_256', CONCAT(customer_id, ':', email)), 2)) AS row_sha256
FROM users;

Oracle

Oracle
SELECT
    LOWER(RAWTOHEX(STANDARD_HASH(email, 'MD5'))) AS email_md5,
    LOWER(RAWTOHEX(STANDARD_HASH(customer_id || ':' || email, 'SHA256'))) AS row_sha256
FROM users;

Questions that come up

SQLite has no hash functions?

The SQLite library itself has none. The sqlite3 command-line shell bundles a sha3() function and the sha1/sha3 extensions ship in the source tree, but an application linking plain SQLite will not have them; compute the hash in application code or store it in a column.

Keep reading

// snippets are better with a schema brain

Run these with autocomplete that knows your tables

SQLly is a native SQL workbench for macOS, Windows and Linux. Paste a snippet into a live connection and you get schema-aware IntelliSense, a plan viewer and guards against unsafe edits.