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 thetable
SET hash = md5(accountid || accounttype || createdby || editedby);
I am later using the hash to compare uniqueness so null hash does not work for this use case.
The problem was the way it handles concatenating nulls. For example:
thedatabase=# SELECT accountid || accounttype || createdby || editedby
FROM thetable LIMIT 5;
1Type113225
<NULL>
2Type11751222
3Type10651010
4Type10651
I could use coalesce or CASE statements if I knew the type; however, I have many tables and I will not know the type ahead of time of every column.
There is much more elegant solution for this.
In Postgres, using table name in
SELECTis permitted and it has typeROW. If you cast this to typeTEXT, it gives all columns concatenated together in string that is actually JSON.Having this, you can get
md5of all columns as follows:If you want to only use some columns, use
ROWconstructor and cast it toTEXT:Another nice property about this solution is that
md5will be different forNULLvs. empty string.Obligatory SQLFiddle.