0

I have an inventory table which contains item_id and the quantity remaining of the item (And also some other meta data). I have an administrator update the inventory by uploading a CSV file which contains the item_id and the quantity remaining.

  1. Run `update for each row in the CSV file. If my CSV file contains 1 million rows, I will end up sending 1 million update statements from my application server to the database server.
  2. Construct 1 million update queries and send them in a batch (JDBC allows batched statements)

At first glance approach number 2 looks like a better solution. But then can 1 million statements be batched? What happens if one of the statement fails for some reason?

1 Answer 1

2

The usual way is to import the CSV file into a staging table. Either an unlogged table which you only create once, or a temp table which you create immediately before the import.

Something along the lines:

create temp table inventory_import (item_id integer primary key, quantity integer);
copy inventory_import from '/path/to/file.csv' ... ;

update inventory i
  set quantity = im.quantity
from inventory_import im
where i.item_id = im.item_id;
11
  • 1
    If you use a low fillfactor and don't update any indexed columns, performance will be even better. Commented Sep 17, 2020 at 6:32
  • @a_horse_with_no_name But how do you drive this flow from application layer? I mean you will have a good amount of users uploading CSV files to make changes to inventory that they care about.
    – Ashwin
    Commented Sep 17, 2020 at 6:35
  • I think this approach makes sense as a one time update that you would do when you are within the database machine, right?
    – Ashwin
    Commented Sep 17, 2020 at 6:36
  • @Ashwin: with multiple users, you can use one temp table for each user.
    – user1822
    Commented Sep 17, 2020 at 6:40
  • Postgres has no problem updating 1Μ rows in a single transaction? Commented Sep 17, 2020 at 7:30

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.