SCD2 implementation in PostgreSQL with 'create rule/trigger'

576 views Asked by At

I wanted to implement SCD2 in postgreSQL. For now, I am trying with 'create rule' as I wanted to update primary table(MAIN for example) based on staging table (STG for example which is truncate and load).

So whenever there is insert in staging table (STG), below operations should be performed AUTOMATICALLY.

  1. Insert into MAIN/Primary table (MAIN) if its new record (present in STG but not in MAIN), set flag=1.

  2. and below 2 sqls i. Update non-key records of main table (MAIN) if its already present from stage table (STG) and set active flag =1. ii. Mark old record to inactive may be with flag set to 0 in MAIN table.

I am trying something below but its not working. Please suggest the better approach/correct SQLs. It can be with rule/trigger.

--SQL to UPDATE record in MAIN table as active record with flag=1.

create rule r_upd as on insert to STG 
where (exists (select 1 from STG where STG.id=NEW.id))
do 
     update MAIN set flag=1 where id=NEW.id;
--
There is one more rule (or can be done in one SQL) required which can set old record to inactive (FLAG=0) 
--
    
-- 
--SQL to INSERT recrord in MAIN table as active record with flag=1
create rule r_ins as on insert to STG 
do 
     insert into MAIN 
     select id, 1 from STG where id not in (select id from MAIN);

thank you.

0

There are 0 answers