Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I drop all indexes of a table in Postgres?

Tags:

I keep having this problem: I have like 20 indexes on a table that I need to drop in order to do testing. Dropping the table doesn't drop all of this metadata.

There doesn't seem to be a wildcard drop index ix_table_* or any useful command. There seem to be some bash loops around psql you can write.
There must be something better! Thoughts?

like image 816
Erin Avatar asked Dec 01 '15 00:12

Erin


People also ask

Does dropping a table drop all indexes?

Dropping a table removes the table definition from the data dictionary. All rows of the table are no longer accessible. All indexes and triggers associated with a table are dropped.

How do you delete a index from a table in Postgres?

In PostgreSQL, the DROP INDEX statement to remove an existing index. Syntax: DROP INDEX [ CONCURRENTLY] [ IF EXISTS ] index_name [ CASCADE | RESTRICT ]; Let's analyze the above syntax: index_name : This is used to specify the name of the index that you want to remove after the DROP INDEX clause.

Does dropping a table drop the index Postgres?

DROP TABLE removes tables from the database. Only the table owner, the schema owner, and superuser can drop a table. To empty a table of rows without destroying the table, use DELETE or TRUNCATE . DROP TABLE always removes any indexes, rules, triggers, and constraints that exist for the target table.


1 Answers

Assuming you only want to drop plain indexes:

DO $do$ DECLARE    _sql text; BEGIN       SELECT 'DROP INDEX ' || string_agg(indexrelid::regclass::text, ', ')    FROM   pg_index  i    LEFT   JOIN pg_depend d ON d.objid = i.indexrelid                           AND d.deptype = 'i'    WHERE  i.indrelid = 'table_name'::regclass  -- possibly schema-qualified    AND    d.objid IS NULL                      -- no internal dependency    INTO   _sql;        IF _sql IS NOT NULL THEN                    -- only if index(es) found      EXECUTE _sql;    END IF; END $do$; 

Does not touch indexes created as implementation detail of constraints (UNIQUE, PK, EXCLUDE).
The documentation:

DEPENDENCY_INTERNAL (i) 

The dependent object was created as part of creation of the referenced object, and is really just a part of its internal implementation.

You could wrap this in a function for repeated execution.
Related:

  • Table name as a PostgreSQL function parameter

Related:

  • DROP FUNCTION without knowing the number/type of parameters?

Aside: This is a misunderstanding:

Dropping the table doesn't drop all of this metadata.

Dropping a table always cascades to all indexes on the table.

like image 115
Erwin Brandstetter Avatar answered Sep 24 '22 17:09

Erwin Brandstetter