I'm using PostgreSQL 9.3.
I want to duplicate some of the db records. Since I'm using an auto-increment pk id for the table, I want to get back the id mappings from the generated ids of duplicated records to the original ones. For example, say I have a table posts
with 2 records in it:
[{'id': 1, 'title': 'first'}
, {'id': 2. 'title': 'second'}]
With SQL:
INSERT INTO posts (title) SELECT title FROM posts RETURNING id, ??
I expect to see mappings like:
[{'id': 3, 'from_id': 1}
, {'id': 4, 'from_id': 2}]
Any idea on how to fill in the question marks above to make it work? Thanks a lot!
This would be simpler for
UPDATE
, where additional rows joined into the update are visible to theRETURNING
clause:The same is currently not possible for
INSERT
. Per documentation:table_name being the target of the
INSERT
command.You can use (data-modifying) CTEs to get this to work.
Assuming
title
to be unique per query, else you need to do more:If
title
is not unique per query (but at leastid
is unique per table):This second query relies on the undocumented implementation detail that rows are inserted in the order provided. It works in all current versions of Postgres and is probably not going to break.
SQL Fiddle.
if
id
column ofposts
generated bynextval('posts_id_seq'::regclass)
you can manually call this function for every new rowit'l works with any data, include non-unique
title
The simplest solution IMHO would be to simply add a column to your table where you could put id of the row that was cloned.