Skip to content
Advertisement

Sqlite executemany and DELETE

Execute many seems to be very slow with deletion (Insertion is fine) and I was wondering if anyone knows why it takes so long.

Consider the code below:

JavaScript

And the following time results (timeit was giving funny data so :/) from IPython:

JavaScript

And just for the sake of completeness here are the timeit results (but I think timeit is broken on the second test(that or the ms is a different unit then the first test))

JavaScript

So why is executemany soooooo slow with deletes?

Advertisement

Answer

SQLites stores table records in a B+ tree, sorted by rowid.

When you are inserting with an automatically generated rowid, all records are just appended at the end of the table. However, when deleting, SQLite has to search for the record first. This is slow if the id column is not indexed; either create an explicit index (as proposed by John), or declare the column as INTEGER PRIMARY KEY to make it the rowid.

Inserting with an index becomes faster if you don’t use the index, i.e., if you create the index only after bulk inserts.

Your last delete command deletes all records at once. If you know that you’re deleting all records in the table, you could speed it up even further by using just DELETE FROM testing, which doesn’t need to look at any records at all.

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