Search code examples
phpmysqlhashchecksum

Generating a checksum or hash for field values of a record


I want to have a column containing a hash or checksum as a single value to compare records. Is it possible to do something like this in pure SQL ? Do you see this as practical versus a programmatic solution in PHP ?


Solution

  • Yes, this is possible. MD5(), SHA1(), and SHA2() are all workable hash functions.

    You must compute the values of these functions row by row and query by query. For example, every time you insert a row you'll have to insert the hash value, doing something like this:

    INSERT INTO x
           name=?name,
           address=?address,
           hash=MD5(CONCAT(?name,?address))
    

    You'll need to do something similar on each update. If you get it wrong, which is remarkably easy especially if your table structure changes, your hashes become worse than useless.

    By the way, MD5 isn't cryptographically secure for authentication any more. However, it's still an acceptable choice for this kind of hashing in a closed system.