Skip to content

Instantly share code, notes, and snippets.

@Calcifer777
Created November 1, 2020 10:57
Show Gist options
  • Save Calcifer777/b2a2b5890151d6aa5d14978f1c6561e0 to your computer and use it in GitHub Desktop.
Save Calcifer777/b2a2b5890151d6aa5d14978f1c6561e0 to your computer and use it in GitHub Desktop.
postgres scd2 (slow changing dimension) trigger implementation
create table records (
record_id int,
record_name varchar(100),
record_value int,
date_start timestamp default now(),
date_end timestamp default null,
primary key(record_id, record_name, date_start)
);
insert into records (record_id, record_name, record_value)
values
(1, 'r1', 30),
(2, 'r2', 42)
;
select * from records;
CREATE OR REPLACE function public.scd2()
returns trigger
AS $BODY$
BEGIN
update records
set date_end = now()
where record_name=new.record_name
and date_end is null;
return new;
END;
$BODY$
LANGUAGE plpgsql;
CREATE TRIGGER example_trigger before INSERT ON records
FOR EACH ROW EXECUTE PROCEDURE scd2();
insert into records (record_id, record_name, record_value)
values
(1, 'r1', 45)
;
select * from records;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment