Skip to content
Advertisement

how can i loop insert query?

I have a problem like this: I need to optimize the application, with db (postgreSQL), the table looks like this:

I have more than a thousand such voters, and I need to put all of them in the database, but among them there are several duplicates that could vote several times (from 2 to infinity), and I need to, when meeting such a duplicate, increase the count field for an existing one (for a voter with the same name and birthdate). Previously, I just checked whether there is such a voter in the table or not, and if there is, then find it and increase the count.

But the program worked for too long, and I tried to do it through MULTI INSERT and use ON CONFLICT DO UPDATE to increase count, but I get an error, then I asked a question on stackoverflow, and I was offered to do a lot of INSERTs, through a loop, but in PostgreSQL.

Question: how to do INSERT in a loop through PostgreSQL.

Advertisement

Answer

Probably the best option is to insert before all the data in a table without primary key, for instance:

and then insert the data with a single statement:

Note that if you have the data in a structured text file (for instance a CSV file), you can insert all the data into voter_count_with_duplicates with a single COPY statement.

If you have to insert (a lot of) new data with the table already populated, there are several possibilities. One is to use the solution in the comment. Another one is to perform an an update and an insert:

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement