Lets say that I have two tables.
The first is: table lists, with list_id SERIAL, list_name TEXT
The second table is, trivially, a table which says if the list is public: list_id INT, is_public INT
Obviously a bit of a contrived case, but I am planning out some tables and this seems to be an issue. If I insert a new list_name into table lists, then it’ll give me a new serial number…but now I will need to use that serial number in the second table. Obviously in this case, you could simply add is_public to the first table, but in the case of a linking list where you have a compound key, you’ll need to know the serial value that was returned.
How do people usually handle this? Do they get the return type from the insert using whatever system they’re interacting with the database with?
One approach to this sort of thing is:
INSERT...SELECT lastval()INSERT...INSERT into the first table, use
lastval()to get the “value most recently obtained withnextvalfor any sequence” (in the current session), and then use that value to build your next INSERT.There’s also
INSERT ... RETURNING:Using
INSERT ... RETURNING idbasically combines the first two steps above into one so you’d do:INSERT ... RETURNING idINSERT ...where the second INSERT would use the
idreturned from the first INSERT.