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?
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.
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.
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.
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:
Related:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With