Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pgsql. Returning field as insert result in function

Tags:

I can return id as an INSERT result, like

INSERT INTO table(id,field) VALUES($id,$value) RETURNING id; 

But i cannot return it and assign to variable into my function

var = INSERT INTO table(id,field) VALUES($id,$value) RETURNING id; 

or

SELECT INTO var INSERT INTO table(id,field) VALUES($id,$value) RETURNING id; 

don't work. How can i do it?

like image 550
dio_bless Avatar asked Aug 20 '13 13:08

dio_bless


People also ask

What does Postgres return on insert?

It can contain column names of the command's target table, or value expressions using those columns. A common shorthand is RETURNING * , which selects all columns of the target table in order. In an INSERT , the data available to RETURNING is the row as it was inserted.

Can we commit inside a function in PostgreSQL?

A Postgres FUNCTION is always atomic (runs inside a single transaction wrapper) and cannot handle transactions. So COMMIT is disallowed.

Can Postgres procedure return a value?

A PROCEDURE can return values, but in a very limited fashion (as of Postgres 13). The manual on CALL : CALL executes a procedure. If the procedure has any output parameters, then a result row will be returned, containing the values of those parameters.

What is Upsert in PostgreSQL?

The UPSERT statement is a DBMS feature that allows a DML statement's author to either insert a row or if the row already exists, UPDATE that existing row instead. That is why the action is known as UPSERT (simply a mix of Update and Insert).


2 Answers

Try this:

INSERT INTO table(id,field) VALUES($id,$value) RETURNING id into var; 
like image 186
Roman Pekar Avatar answered Oct 21 '22 00:10

Roman Pekar


You could also use:

var := (INSERT INTO table(id,field) VALUES($id,$value) RETURNING id); 

Readability is of course a personal preference, but I like this syntax because it shows an obvious assignment.

like image 40
Kirk Roybal Avatar answered Oct 21 '22 00:10

Kirk Roybal