Postgres delete is very slow, how to improve?

My request

delete from test.t1 where t2_id = 1;

      

My main table is t1 (includes about 1M rows and needs to delete about 100k rows)

CREATE TABLE test.t1
(
  id bigserial NOT NULL,
  t2_id bigint,
  ... other fields
  CONSTRAINT pk_t1 PRIMARY KEY (id),
  CONSTRAINT fk_t1_t2 FOREIGN KEY (t2_id)
      REFERENCES test.t2 (id) MATCH SIMPLE
      ON UPDATE NO ACTION ON DELETE NO ACTION
)

      

I have an index for t2_id and 3 other indexes on string strings.

CREATE INDEX t1_t2_idx ON test.t1 USING btree (t2_id);

      

There are several (about 50) tables referencing test.t1. I have an index on t1_id for every table that references it.

CREATE TABLE test.t7
(
  id bigserial NOT NULL,
  t1_id bigint,
  ... other fields
  CONSTRAINT pk_objekt PRIMARY KEY (id),
  CONSTRAINT fk_t7_t1 FOREIGN KEY (t1_id)
      REFERENCES test.t1 (id) MATCH SIMPLE
      ON UPDATE NO ACTION ON DELETE NO ACTION
)

CREATE INDEX t7_t1_idx ON test.t7 USING btree (t1_id);
//No other indexes here

      

The contents of t7 are removed before t1, which is very fast compared to removing from t1. The ratio of lines to delete is the same (~ 10%), but the total number of lines is much less (about 100k).

I was unable to shorten the time to a reasonable length:

  • I tried to delete all indexes (canceled after 24 hours)
  • Only t1_t2_idx and t7_t1_idx ... t50_t1_idx indexes saved (canceled after 24 hours)
  • All indexes saved (canceled after 24 hours)

Also vacuum analysis is done before deletion and there should be no locks (only active query in db).

I haven't tried copying to a temp table and truncating t1, but that doesn't seem sensible since t1 can grow to 10M rows, of which 1M needs to be deleted at some point.

Any ideas for better removal?

EDIT

Quite sure there are no locks because pg_stat_activity only shows 2 active requests (delete and pg_stat_activity)

"Delete on test.t1 (cost=0.43..6713.66 rows=107552 width=6)"
"  ->  Index Scan using t1_t2_idx on test.t1 (cost=0.43..6713.66 rows=107552 width=6)"
"        Output: ctid"
"        Index Cond: (t1.t1_id = 1)"

      

+3


source to share





All Articles