sha256 Content Hash Dedups Uploads
Deduplicate uploads by content: a generated sha256 column plus a unique expression index rejects the second identical payload at insert time.
Code
CREATE TABLE uploads (
id int GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
content text NOT NULL,
content_hash bytea GENERATED ALWAYS AS (sha256(convert_to(content, 'UTF8'))) STORED
);
-- 内容寻址:表达式唯一索引让同内容第二行直接违反约束
CREATE UNIQUE INDEX uploads_hash_unique ON uploads (content_hash);
INSERT INTO uploads (content) VALUES ('report-v1');
INSERT INTO uploads (content) VALUES ('report-v2');
DO $$
BEGIN
INSERT INTO uploads (content) VALUES ('report-v1');
RAISE NOTICE 'duplicate accepted';
EXCEPTION
WHEN unique_violation THEN
RAISE NOTICE 'duplicate rejected: same content hash';
END $$;
SELECT id, content, encode(content_hash, 'hex') AS hash_hex FROM uploads ORDER BY id;What the code does
SELECT / INSERT / CREATE statements share the script, touching uploads.
Breaking the statements into their working parts: an ORDER BY that fixes the output order; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity; UNIQUE constraints that keep duplicate values out; a GENERATED ALWAYS/GENERATED BY clause that computes the column value.
Applying it
Run the statement against the uploads table.
Statements that matter
DO $$
BEGIN
INSERT INTO uploads (content) VALUES ('report-v1');
RAISE NOTICE 'duplicate accepted';
EXCEPTION
WHEN unique_violation THEN
RAISE NOTICE 'duplicate rejected: same content hash';
END $$;
CREATE TABLE uploads (
id int GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
content text NOT NULL,
content_hash bytea GENERATED ALWAYS AS (sha256(convert_to(content, 'UTF8'))) STORED
);
SELECT id, content, encode(content_hash, 'hex') AS hash_hex FROM uploads ORDER BY id;
Interactive Tools for This Topic
SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.SHA-256 Hash GeneratorGenerate SHA-256 cryptographic hashes from text input using the Web Crypto API. Compare hashes and verify data integrity with hexadecimal digest output.SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.
FAQ
- Which tables does the SQL touch?
- `uploads`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.