1

I want to somehow hash the result of a query in PostgreSQL. I have a query like SELECT output FROM result;

And it returns a column composed only of integers. So I somehow want to hash the result of this query. Concatenate the values and hash, or somehow hash the query output directly. Simply I need a way to put it inside SELECT sha256(...). So please note that I do not want to get hash of every column entry, but one hash that somehow corresponds to the query output. Any ideas?

2 Answers 2

3

PostgreSQL doesn't come with a built-in streaming hash function exposed to the user, so the easiest way is to build the string in memory and then hash it. Of course this won't work with giant result sets. You can use digest from the pg_crypto extension. You also need to order your rows, or else you might get different results on the same data from one execution to the next if you get the rows in different orders.

select digest(string_agg(output::text,' ' order by output),'sha256')
from result;
Sign up to request clarification or add additional context in comments.

Comments

1

Replace 1234 with your column name and add [from table_name] to this query:

select encode(digest(1234::text, 'sha256'), 'hex')

Or for multiple rows use this:

select encode(
    digest(
           (select array_agg(q1)::text[] from (select row(R.*)::text as q1 from (SELECT output FROM result)R)alias)::text
    , 'sha256')
   , 'hex')

1 Comment

This is perfect. NOTE: I had to run CREATE EXTENSION IF NOT EXISTS pgcrypto; to enable the pgcrypto and be able to use the digest function.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.