Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firebird truncate table / delete all rows

I am using Firebird 2.5.1 Embedded. I have done the usual to empty the table with nearly 200k rows:

delete from SZAFKI

Here's the output, see as it takes 16 seconds, which is, well, unacceptable.

Preparing query: delete from SZAFKI
Prepare time: 0.010s
PLAN (SZAFKI NATURAL)

Executing...
Done.
3973416 fetches, 1030917 marks, 116515 reads, 116434 writes.
0 inserts, 0 updates, 182658 deletes, 27 index, 182658 seq.
Delta memory: -19688 bytes.
SZAFKI: 182658 deletes. 
182658 rows affected directly.
Total execution time: 16.729s
Script execution finished.

Firebird has no TRUNCATE keyword. As the query uses PLAN NATURAL, I tried to PLAN the query by hand, like so:

delete from szafki PLAN (SZAFKI INDEX (SZAFKI_PK))

but Firebird says "SZAFKI_PK cannot be used in the specified plan" (it is a primary key) Question is how do i empty table efficiently? Dropping and recreating is not possible.

like image 546
Kitet Avatar asked Jan 15 '23 19:01

Kitet


2 Answers

Answer based on my comment

A trick you could try is to use DELETE FROM SZAFKI WHERE ID > 0 (assuming the ID is 1 or higher). This will force Firebird to look up the rows using the primary key index.

My initial assumption was that this would be worse than an unindexed delete. An unindexed delete will do a sequential scan of all datapages of a table and delete rows (that is: create a new recordversion that is a deleted stub record). When you use the index it will lookup rows in index order, this will result in a random walk through the datapages (assuming a high level of fragmentation in the data due to a high number of record versions due to inserts, deletes and updates). I had expected this to be slower, but probably it will result in Firebird having to only read the relevant datapages (with record versions relevant to the transaction) instead of all datapages of a table.

like image 129
Mark Rotteveel Avatar answered Jan 17 '23 10:01

Mark Rotteveel


Unfortunately, there is no fast way to do massive delete on entire (big) table with currently Firebird versions. You can expect even higher delays when the "deleted content" is garbage collected (run select * in the table after the delete is committed and you will see). You can try to deactivate indexes in that table before doing the delete and see if it helps. If you are using the table as some kind of temporary storage, I suggest you to use the GTT feature.

like image 20
WarmBooter Avatar answered Jan 17 '23 09:01

WarmBooter