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

634
Views
How to use variables in PostgreSQL transaction

How in Postgresql inside a transaction to get values ​​into a variable, and if SELECT did not return anything, throw an error, and if SELECT returned data, then use them in the transaction?

Like this:

BEGIN;

@activeRounds = SELECT * FROM "rounds" WHERE status = 'active';

if(!@activeRounds) {
  RAISE ERROR "Has no Active rounds"
};

INSERT INTO "bet"
  (user_id, round_id)
VALUES
  (100, @activeRound[0].id)


COMMIT;

how to do something similar in one request within a transaction?

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

You can adapt following code to your table structure:

begin;
do
$$
declare
 v int;
begin
 select c1 into v from t1 where  k1=1;
 if not found 
 then
  raise exception 'no row found';
 else
  insert into t2(c2) values(v);
 end if;
end;
$$;
commit;

Note the difference bewteen begin; to start a transaction and begin to start a pl/pgSQL block.

over 4 years ago · Santiago Trujillo Report

0

Write a DO statement in PL/pgSQL.

Like every SQL statement, DO runs in a single transaction. PL/pgSQL is a procedural language that has variables and conditional processing.

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!