I have a python3 code, where I'm inserting data into a postgres table, where the table has a SERIAL integer column, whose value I would like to return after insert.
I have tried using 'Returning', but did not get the ID returned in response
query = INSERT INTO table ({{table_columns}}) VALUES ({{table_values}}) RETURNING id;
response = cur.execute(query)
Found help in using into but that was still returning nothing, also tried selecting the defined variable value.
DO $$
DECLARE tableId integer;
BEGIN
INSERT INTO table ({{table_columns}}) VALUES ({{table_values}}) RETURNING id INTO tableId;
SELECT tableId;
END $$;
This threw an error.
response = cur.execute(query)
psycopg2.errors.SyntaxError: query has no destination for result data
HINT: If you want to discard the results of a SELECT, use PERFORM instead.
CONTEXT: PL/pgSQL function inline_code_block line 5 at SQL statement
How to access the value returned in tableId outside from Python after query execution ? Any other alternative solution of returning the id value is also welcome.
Postgres Version 11.2
DOblack can not return anything. You will need to wrap your INSERT into a function if you want to do that.. That would need to bePERFORM tableid` to makeplpgsqlhappy. It is not going to solve the issue ofDOblocks not returning anything. Also in a regular function it would not help either as you would not actually be returning the value. That would requireRETURN tableId;and the correctRETURNSat the top of the function definition.