I have created these two tables:
CREATE TABLE Purchase(
purchaseID SERIAL,
custName VARCHAR(30) NOT null,
PRIMARY KEY (purchaseID));
CREATE TABLE PurchasedItem(
You can use lastval()
INSERT INTO Purchase(custName) VALUES ('Lendl');
INSERT INTO PurchasedItem(purchaseID, itemNo) VALUES (lastval(), 111);
commit;
Alternatively query the underlying sequence directly:
INSERT INTO Purchase(custName) VALUES ('Lendl');
INSERT INTO PurchasedItem(purchaseID, itemNo)
VALUES (currval('purchase_purchaseid_seq'), 111);
commit;
Or if you don't want to rely on the automatic naming of the sequence, use pg_get_serial_sequence
to get the sequence associated with the column:
INSERT INTO Purchase(custName) VALUES ('Lendl');
INSERT INTO PurchasedItem(purchaseID, itemNo)
VALUES (currval(pg_get_serial_sequence('purchase', 'purchaseid')), 111);
commit;
For more details see the manual: https://www.postgresql.org/docs/current/static/functions-sequence.html
DEFAULT
will work for SERIAL
as it sets default value for column. So
INSERT INTO Purchase VALUES (DEFAULT,'Lendl');
should work. But PurchasedItem.purchaseID
has no default value set, so it it tries to insert NULL
(and null is not in referenced column yet), so it fails.
try:
INSERT INTO Purchase(custName) VALUES ('Lendl') RETURNING purchaseID;
you will see the value of inserted purchaseID
, use it in next query:
INSERT INTO PurchasedItem(purchaseID, itemNo) VALUES (_the_value_above_, 111);
commit;
If you want it to be used without interactivity, use DO
block with returning purchaseID into _value
update:
or cte, smth like
WITH i AS (
INSERT INTO Purchase(custName, orderedDate)
VALUES ('Lendl', '2016-09-28')
RETURNING purchaseID
)
insert into PurchasedItem
select i.purchaseID,'smth',3
from i