Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Postgres insert optimization

I have a script that generates tens of thousands of inserts into a postgres db through a custom ORM. As you can imagine, it's quite slow. This is used for development purposes in order to create dummy data. Is there a simple optimization I can do at the Postgres level to make this faster? It's the only script running, sequentially, and requires no thread safety.

Perhaps I can turn off all locking, safety checks, triggers, etc? Just looking for a quick and dirty solution that will greatly speed up this process.

Thanks.

like image 658
Scott Klarenbach Avatar asked Dec 03 '10 18:12

Scott Klarenbach


2 Answers

If you don't need that kind of functionality in production environment, I'd suggest you turn fsync off from your PostgreSQL config. This will speed up the inserts dramatically.

Never turn off fsync on a production database.

like image 194
jmz Avatar answered Sep 22 '22 12:09

jmz


The fastest way to insert data would be the COPY command. But that requires a flat file as its input. I guess generating a flat file is not an option.

Don't commit too often, especially do not run this with autocommit enabled. "Tens of thousands" sounds like a single commit at the end would be just right.

If you can convice your ORM to make use of Postgres' multi-row insert that would speed up things as well

This is an example of a multi-row insert:

insert into my_table (col1, col2) 
values 
(row_1_col_value1, row_1_col_value_2), 
(row_2_col_value1, row_2_col_value_2), 
(row_3_col_value1, row_3_col_value_2)

If you can't generate the above syntax and you are using Java make sure you are using batched statements instead of single statement inserts (maybe other DB layers allow something similar)

Edit:

jmz' post inspired me to add something:

You might also see an improvement when you increase wal_buffers to some bigger value (e.g. 8MB) and checkpoint_segments (e.g. 16)

like image 27
a_horse_with_no_name Avatar answered Sep 25 '22 12:09

a_horse_with_no_name