Alter Table Set Statistics requires table lock

4.5k views Asked by At

I have run into a case such that Pg always preferring into a sequential scan for a table that has around 70M rows. (Index scan is ideal for that query and i have confirmed it by setting enable_seq_scan=off, speed improved by 200x)

So, in order to help Pg understand my data better i executed this

ALTER TABLE tablename ALTER COLUMN columnname SET STATISTICS 1000;

Unfortunately this requires Update Exclusive lock which locks the entire table (too much lock).

  1. Is there a solution to avoid locking for this statement ?
  2. Data sharding is done for this table based on Primary Key Range, so I would like Pg to even understand my Pk better so that it knows which User has got large data. Will it be of use if i increase the statistics of PrimaryKey column as well ?
1

There are 1 answers

9
Evan Carroll On

From the very docs you linked

SET STATISTICS

This form sets the per-column statistics-gathering target for subsequent ANALYZE operations. The target can be set in the range 0 to 10000; alternatively, set it to -1 to revert to using the system default statistics target (default_statistics_target). For more information on the use of statistics by the PostgreSQL query planner, refer to Section 14.2.

SET STATISTICS acquires a SHARE UPDATE EXCLUSIVE lock.

And, on the docs for Explicit Locking

SHARE UPDATE EXCLUSIVE Conflicts with the SHARE UPDATE EXCLUSIVE, SHARE, SHARE ROW EXCLUSIVE, EXCLUSIVE, and ACCESS EXCLUSIVE lock modes. This mode protects a table against concurrent schema changes and VACUUM runs.

Acquired by VACUUM (without FULL), ANALYZE, CREATE INDEX CONCURRENTLY, and ALTER TABLE VALIDATE and other ALTER TABLE variants (for full details see ALTER TABLE).

So you can't change the schema, or vacuum while analytics are happening. So what? They should happen very fast. Almost instantly.