Getting a quick hash of a query in PostgreSQL

I’ve been doing a lot of tweaking of SQL queries as of late, trying to squeeze some performance out of a query by adding indexes, optimizing joins, and some other operations. To do a quick check to ensure that the queries return the same results, I’ve been hashing the results to see if I get an identical hash back.

md5(CAST((array_agg(f.* ORDER BY id)) AS TEXT)) as md5,
      (array_agg(f.* ORDER BY AS TEXT
'hex') as sha1
FROM foo f;

This solution was adapted from

sha1 requires pgcrypto to be installed.

This solution looks at individual rows. I have also covered how to hash an entire query result set.

Leave a Reply