I am writing a function in PostgreSQL. It does basically 3 steps:
- Fetch a record from source table.
- check the value from the fetched record in target table, if record is found in target table then update all values of target table with fetched record otherwise insert fetched record to target table.
Instead of doing this looping, if I write single query for insert/update, will it be faster than above mentioned approach? How can I achieve same result by writing single query instead looping through every records and doing updation/insertion.
My current approach is as below
CREATE OR REPLACE FUNCTION fun1()
RETURNS void AS
$BODY$DECLARE
source_tab_row RECORD;
v_col1 TEXT;
v_col2 TEXT;
v_col3 TEXT;
v_col4 double precision ;
cnt integer;
BEGIN
FOR source_tab_row IN (SELECT * FROM source_tab where col5='abc')
LOOP
v_col1=source_tab_row.col1;
v_col2=source_tab_row.col2;
v_col3=source_tab_row.col3;
v_col4=source_tab_row.col4;
select count(*) INTO cnt from dest_tab where col1=v_col1;
if (cnt =0) then
-- If records is not found
INSERT INTO dest_tab(col1, col2, col3,col4)
VALUES( v_col1, v_col2, v_col3,v_col4) ;
else
--if records found then update it
update dest_tab set col1=v_col1, col2=v_col2, col3=v_col3,col4=v_col4
where col1=v_col1;
end if;
END LOOP;
END;
$BODY$ LANGUAGE plpgsql;