// SQL snippet

Compute a checksum over a table

Concatenate each row's columns into a stable string, hash it, then aggregate all row hashes into a single value that changes when any row does.

Main statement
PostgreSQL
同時涵蓋
SQL Server

The task

Two environments should hold identical orders data. Comparing every row is too slow over the wire; one checksum per table is enough to say whether they differ.

The snippet

Written for PostgreSQL. Versions for SQL Server are under Variations.

PostgreSQL
SELECT MD5(STRING_AGG(MD5(CAST(o AS TEXT)), ',' ORDER BY o.id)) AS table_checksum
FROM orders o;

它的運作方式

CAST(o AS TEXT) turns the whole row into its text form, such as (6,,2026-01-07,,paid,0.01,...), with every column in table order and NULLs as empty fields, and MD5 hashes it. Hand-concatenating columns with || is the classic mistake here: one NULL column makes the whole string NULL, STRING_AGG skips it, and that row silently drops out of the checksum. STRING_AGG with ORDER BY o.id folds the row hashes in a fixed order, so the result does not depend on how rows are stored, and the outer MD5 reduces it to 32 hex characters. Any changed, inserted or deleted row changes it. Both sides must have the same column order and types for the text forms to match.

Variations

SQL Server: CHECKSUM_AGG (order-independent, weak)

SQL Server
SELECT CHECKSUM_AGG(BINARY_CHECKSUM(*)) AS table_checksum
FROM orders;

Cheap portable fingerprint (no hash functions)

SELECT COUNT(*) AS row_count,
       SUM(id) AS id_sum,
       MAX(id) AS max_id,
       MAX(updated_at) AS last_change
FROM orders;

Questions that come up

Can two different tables share a checksum?

With MD5 an accidental collision is vanishingly unlikely. SQL Server's BINARY_CHECKSUM and CHECKSUM_AGG are a different matter: they return 32-bit integers, so unrelated changes can produce the same value, and Microsoft's docs warn that CHECKSUM_AGG can miss changes. For a stronger hash use sha256() (built into PostgreSQL 11+) or HASHBYTES('SHA2_256', ...) on SQL Server, and confirm any mismatch with a row-level diff.

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.