Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get full CREATE INDEX clause for existing index in pure SQL?

Tags:

postgresql

I've wrote a simple script to reindex our PG databases once a week. It has a simple logic:

  • get top 10 indices by amount of bloated bytes
  • lookup create index clause from hashmap variable (index name -> create clause)
    • if there is none - log to stderr and go to next index
  • create new index concurrently
  • drop old index concurrently
  • rename new index

And being proper lazy developer I dislike this concept that I have to constantly update my hashmap. (On the other hand, I have found two inefficient indices while doing that.)

pg_index seems quite informative, is there a way to reconstruct a create index clause from it?

It's easy to get columns list, but we use different index types, different opclasses for fields, partial indices... And who knows what. It's important to be sure that we will get exact the same clause that was used to create index in the first place.

like image 692
skaurus Avatar asked Sep 21 '14 11:09

skaurus


People also ask

How do I add an index to an existing table?

ALTER command to add and drop INDEXALTER TABLE tbl_name ADD INDEX index_name (column_list) − This adds an ordinary index in which any value may appear more than once. ALTER TABLE tbl_name ADD FULLTEXT index_name (column_list) − This creates a special FULLTEXT index that is used for text-searching purposes.

Why we need to create an index if the primary key is already present in a table?

32) Why we need to create an index if the primary key is already present in a table? Primary key can store null value, whereas a unique key cannot store null value.

What is the correct syntax for creating an index?

Syntax. The syntax to create an index in SQL is: CREATE [UNIQUE] INDEX index_name ON table_name (column1, column2, ... column_n);

How many indexes can be created on a table in SQL Server?

Each table can have up to 999 nonclustered indexes, regardless of how the indexes are created: either implicitly with PRIMARY KEY and UNIQUE constraints, or explicitly with CREATE INDEX .


1 Answers

Yep, there's a built-in function pg_get_indexdef for the purpose.

e.g.:

regress=> SELECT pg_get_indexdef('demo_pkey'::regclass);
                    pg_get_indexdef                     
--------------------------------------------------------
 CREATE UNIQUE INDEX demo_pkey ON demo USING btree (id)
(1 row)
like image 87
Craig Ringer Avatar answered Oct 12 '22 13:10

Craig Ringer