13

I have this 3 tables.

Employee
PK : id
name

completedBy
FK : employee_id
FK : order_id

Order
PK : id
date

I created form for creating order where i fill infos of order (date) and who completed order. In my form there is a table from which I select the employee and get his id. I want to know if there is possible to insert into tables Order and completedBy with one single query.

Is there any difference in effectivity between using two inserts or using the code in answer ?

2
  • You could create an stored procedure that execute both inserts Commented Apr 10, 2015 at 14:38
  • I know that it is possible with two inserts. I just want to know if there is a way with one querry so it would be little more effective Commented Apr 10, 2015 at 14:41

1 Answer 1

23

This can be done using a data modifying common table expression:

with new_order as (
  insert into orders (id, date) values (1, current_date)
  returning id
)
insert into completedby (employee_id, order_id)
values 
( 42 -- employee_id, 
  (select id from new_order)
);

The first part inserts into the orders table and returns the ID that was inserted. The second part then inserts the row into the completedby table using the known employee_id and retrieving the order_id from the previous step.

Edit

if the id column in the orders table is a serial column and you want to let the sequence generate the value you can do that as well:

with new_order as (
  insert into orders (date) values (current_date)
  returning id
)
insert into completedby (employee_id, order_id)
values 
( 42 -- employee_id, 
  (select id from new_order)
);
Sign up to request clarification or add additional context in comments.

9 Comments

this statement (select id from new_order) will use returned value ?
@user2938332: yes that's the ID from the first CTE (named new_order)
and is this approach to problem more effective than using two inserts or there is no difference ?
@user2938332 why don't you simply run and test it yourself? Obviously in this case it can not be cheaper than two separate INSERT statements as it is doing exactly that - and a bit more.
A nice example, @a_horse_with_no_name, how would you modify it to include ON CONFLICT (id) UPDATE (upsert) on both tables?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.