SQL Server CHECKSUM and BINARY_CHECKSUM
CHECKSUM(col1, col2) reduces a row to one int, handy for spotting rows that may have changed. It is a quick filter, not a reliable fingerprint.
- Kategorie
- Strings
- Returns
int- In this category
- 172 of 172
Syntax
CHECKSUM(* | expression [, ...])
BINARY_CHECKSUM(* | expression [, ...])
Each block is a separate form. The support table and the examples show which engine takes which.
Engine-Unterstützung
| Engine | Support | Notizen |
|---|---|---|
| SQL Server | Ja | Supported under this name. |
| PostgreSQL | Not built in | no documented equivalent; md5(row::text) for change detection |
| MySQL | Different name or syntax | CRC32(str) for one string |
| SQLite | Not built in | no hash functions in the core library |
| Oracle | Different name or syntax | ORA_HASH(expr [, max_bucket [, seed]]) |
Beispiele
SQL Server
SELECT CHECKSUM('abc') AS ci_lower, CHECKSUM('ABC') AS ci_upper, BINARY_CHECKSUM('abc') AS bin_lower, BINARY_CHECKSUM('ABC') AS bin_upper; -- 34400, 34400, 26435, 17763 under a CI collation
SQL Server
SELECT s.id FROM (VALUES (1, 'a', 10), (2, 'b', 20)) AS s(id, name, qty) JOIN (VALUES (1, 'a', 10), (2, 'b', 25)) AS t(id, name, qty) ON t.id = s.id WHERE BINARY_CHECKSUM(s.name, s.qty) <> BINARY_CHECKSUM(t.name, t.qty); -- 2
Oracle
SELECT ORA_HASH('abc') AS h, ORA_HASH('abc', 9) AS bucket FROM dual; -- 1194017796, 6
Gut zu wissen
- CHECKSUM follows the collation: under a case-insensitive collation CHECKSUM('abc') equals CHECKSUM('ABC'). BINARY_CHECKSUM works on the bytes, so case changes show.
- A 32-bit result collides: different rows can share a checksum. Use it to narrow the candidates, then compare the columns, or use HASHBYTES('SHA2_256', ...) when collisions matter.
- Oracle's ORA_HASH returns 0 to 4294967295 by default and takes a maximum bucket: WHERE ORA_HASH(id, 9) = 0 keeps roughly a tenth of the rows, a common sampling trick.
Questions about CHECKSUM / BINARY_CHECKSUM
CHECKSUM or HASHBYTES?
CHECKSUM is fast and 32-bit, good for a first pass over many rows. HASHBYTES with SHA2_256 is slower but collisions are negligible, so use it when a match must mean 'unchanged'.
Can I index a checksum?
Yes. Add a computed column such as row_chk AS BINARY_CHECKSUM(name, qty) and index it to find candidate matches quickly.
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, 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.