Skip to content

Instantly share code, notes, and snippets.

@kilfu0701
Last active April 5, 2022 12:30
Show Gist options
  • Save kilfu0701/6485abb501536964ab9fc4fb76106819 to your computer and use it in GitHub Desktop.
Save kilfu0701/6485abb501536964ab9fc4fb76106819 to your computer and use it in GitHub Desktop.
[postgres] delete a table's indexes function.
CREATE OR REPLACE FUNCTION rm_table_idx(tbl_name text)
RETURNS void AS
$$
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 = tbl_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
raise notice '%', _sql;
EXECUTE _sql;
END IF;
END;
$$
LANGUAGE plpgsql;
@kilfu0701
Copy link
Author

Usage

select rm_table_idx('public.table_name1');

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment