Skip to content

Instantly share code, notes, and snippets.

@Konard
Created December 5, 2021 12:54
Show Gist options
  • Save Konard/8d2866bcc55192aa24c887b40553419d to your computer and use it in GitHub Desktop.
Save Konard/8d2866bcc55192aa24c887b40553419d to your computer and use it in GitHub Desktop.
PostgreSQL functions to create indexes for all columns of any table.
DROP FUNCTION create_btree_index;
CREATE OR REPLACE FUNCTION create_btree_index(schema_name text, table_name text, column_name text) RETURNS void
AS $$
BEGIN
EXECUTE 'CREATE INDEX IF NOT EXISTS ' || table_name || '__' || column_name || '_btree ON ' || schema_name || '.' || table_name || ' USING btree (' || column_name || ');';
END;
$$ LANGUAGE plpgsql;
DROP FUNCTION create_btree_indexes_for_all_columns;
CREATE OR REPLACE FUNCTION create_btree_indexes_for_all_columns(schema__name text, table__name text) RETURNS void
AS $$
BEGIN
PERFORM create_btree_index(table_schema, table_name, column_name) FROM information_schema.columns
WHERE table_schema = schema__name AND table_name = table__name;
END;
$$ LANGUAGE plpgsql;
select create_btree_indexes_for_all_columns('public', 'table_name');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment