I'm trying to create a generated column with a hash on two columns, but I get error.
What's wrong with my hash?
create table dwh_stage.account_data_src(
id int4 not null,
status_nm text null,
create_dttm timestamp null,
update_dttm timestamp null,
hash bytea NULL GENERATED ALWAYS AS
(digest(COALESCE(status_nm, '#$%^&'::text)
|| date_part('epoch'::text, COALESCE(timezone('UTC'::text, create_dttm), '1990-01-01 00:00:00'::timestamp without time zone))::text, 'sha256'::text))
stored
);
datepart(text, timestamptz)is onlySTABLE, because the result implicitly depends on the currenttimezonesetting. (Well, AFAICT, extracting the epoch would be immutable, but other extracted parts vary with the setting, so the function cannot be markedIMMUTABLE.)But
datepart(text, timestamp)isIMMUTABLE.Your expression is a mess in this regard to begin with. You mix
timestamptzandtimestampin theCOALESCEexpression, which forces the conversion of the giventimestampconstant ...Drop the conversion of
create_dttmtotimestamptzand it works:Note:
create_dttminstead oftimezone('UTC'::text, create_dttm).That said, if a
biginthash is good enough (like it is in many cases), and you run Postgres 14 or later, then consider instead:Much simpler and faster. See: