Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

227
Views
Double INSERT using a TRANSACTION postgres

Good evening,

I want to create a TRANSACTION with the proper isolation level. On that transaction I want to do a double insert and if one fails the other one is aborted.

I have a stored procedure already created:

create or replace function insert_into_answercomments(userid INTEGER, answerid INTEGER, body text)
  returns void language plpgsql as $$
DECLARE result INTEGER;
  insert into publications(body, userid)
  VALUES (body, userid)
  returning publications.publicationid AS publicationid INTO result;

  insert into comments(publicationid) VALUES (result);

  insert into answercomments(commentid, answerid) VALUES (result, answerid);
end $$;

My doubt is if the transaction should be inside the function or if it is a different procedure. How do I create it with a correct isolation level.

Kind Regards

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

transaction cannot be started/ended inside postgres function. If you want some logic, make it inside function. In your case you don't need anything - if first insert generates exception, transaction aborts. But if you need some sophisticated check, make it right in code, eg

if result > 90 then
  insert ...second insert
end if;

to run function in transaction start it outside, eg:

begin;
select * from insert_into_answercomments(1,2);
end;
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!