Results 1 to 2 of 2
  1. #1
    Join Date
    Mar 2010

    Unanswered: Insert data from one table into another table

    I am writing a little program in Python to insert data into PostreSQL tables.

    It takes input from the user, then inputs that data into two tables in PostgreSQL.

    The only problem is, the two tables are related by a Primary Key in one table, but I do not know what that Primary Key is at any time because it is of the SERIAL data type.

    So basically I want to know how (i.e. what query can I use) to get the data posted to the first table and return me the ID of that row that was just posted so it can be inserted as the foreign key in the second table.

    This would probably need to be done in one transaction also...

    Any ideas? Any suggestions would be helpful...

  2. #2
    Join Date
    Aug 2009
    Olympia, WA
    You can either use INSERT RETURNING
    INSERT INTO distributors (did, dname) VALUES (DEFAULT, 'XYZ Widgets')
    RETURNING did;

    Or use currval()
    INSERT INTO distributors (did, dname) VALUES (nextval('foo'), 'XYZ Widgets');
    INSERT INTO distributor_parts (did, part) VALUES (currval('foo'), 'thingamajig');

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts