Postgresql – Postgres random text in JSONB column

postgresqlquery

Following is the query I'm using to scrub some fields in the JSONB column. I'm trying to radomize the first and last name so would like to use something like md5(random()::text) as values.

    update people set
    data = to_jsonb(data) || '{"firstName": "random_text", "lastName": "random_text"}'
    where id = 'b3c09005-7afb-4ad6-922d-76078875e59e';

I tried replacing random_text with md5(...) but I get an error

"DETAIL: Token "md5" is invalid.".

I also tried using || to concat but that didn't work either.

Best Answer

You have to use the md5 hash as a part of the string so you have to concat it

CREATE TABLE people("id" varchar(50), "data" jsonb,"firstName" text, "lastName" text)
    update people set
    data = to_jsonb(data) || ('{"firstName": "' || MD5('PostgreSQL MD5') || '", "lastName": "' || MD5('PostgreSQL MD5') || '"}')::jsonb
    where id = 'b3c09005-7afb-4ad6-922d-76078875e59e';

db<>fiddle here

still md5 is old and not very secure, so you should use a more secure version