How to md5 all columns regardless of type

前端 未结 4 2146
抹茶落季
抹茶落季 2021-02-08 11:40

I would like to create a sql query (or plpgsql) that will md5() all given rows regardless of type. However, below, if one is null then the hash is null:

UPDATE t         


        
4条回答
  •  被撕碎了的回忆
    2021-02-08 12:00

    There is much more elegant solution for this.

    In Postgres, using table name in SELECT is permitted and it has type ROW. If you cast this to type TEXT, it gives all columns concatenated together in string that is actually JSON.

    Having this, you can get md5 of all columns as follows:

    SELECT md5(mytable::TEXT)
    FROM mytable
    

    If you want to only use some columns, use ROW constructor and cast it to TEXT:

    SELECT md5(ROW(col1, col2, col3)::TEXT)
    FROM mytable
    

    Another nice property about this solution is that md5 will be different for NULL vs. empty string.

    Obligatory SQLFiddle.

提交回复
热议问题