How to get id from newly inserted row

9,731 views
Skip to first unread message

Sami Pietilä

unread,
Nov 29, 2015, 10:50:00 AM11/29/15
to sqlalchemy
Hi,

I have postgresql database with "records" table. There is "id" (bigserial unique primary key) column. I need to insert a row in such a way that I get id from newly inserted row.

ins = records.insert()
results = conn.execute(ins)

I was unable to find a code example of how to add "RETURNING" functionality to records.insert() and how to find the id from the results.

Thanks

Mike Bayer

unread,
Nov 29, 2015, 11:53:48 AM11/29/15
to sqlal...@googlegroups.com
Please refer to the SQL Expression Language Tutorial, specifically the
last paragraph in this section:

http://docs.sqlalchemy.org/en/rel_1_0/core/tutorial.html#executing


Using the search box on the side of the documentation with the search
term "returning", you'll get more links that describe both implicit and
explicit use of RETURNING:

http://docs.sqlalchemy.org/en/rel_1_0/core/connections.html?highlight=inserted_primary_key#sqlalchemy.engine.ResultProxy.inserted_primary_key

http://docs.sqlalchemy.org/en/rel_1_0/core/dml.html#sqlalchemy.sql.expression.Insert.returning

http://docs.sqlalchemy.org/en/rel_1_0/dialects/postgresql.html#insert-update-returning

>
> Thanks
>
> --
> You received this message because you are subscribed to the Google
> Groups "sqlalchemy" group.
> To unsubscribe from this group and stop receiving emails from it, send
> an email to sqlalchemy+...@googlegroups.com
> <mailto:sqlalchemy+...@googlegroups.com>.
> To post to this group, send email to sqlal...@googlegroups.com
> <mailto:sqlal...@googlegroups.com>.
> Visit this group at http://groups.google.com/group/sqlalchemy.
> For more options, visit https://groups.google.com/d/optout.

Sami Pietilä

unread,
Nov 30, 2015, 2:40:56 PM11/30/15
to sqlalchemy
Thank you! This kind of approach seems to work well:

ins = records.insert().returning(records.c.id)
result = connection.execute(ins)
row = result.fetchone()
Reply all
Reply to author
Forward
0 new messages