Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

At what level do Postgres index names need to be unique?

In Microsoft SQL Server and MySQL, index names need to unique within the table, but not within the database. This doesn't seem to be the case for PostgreSQL.

Here's what I'm doing: I made a copy of a table using CREATE TABLE new_table AS SELECT * FROM old_table etc and need to re-create the indexes.

Running a query like CREATE INDEX idx_column_name ON new_table USING GIST(column_name) causes ERROR: relation "idx_column_name" already exists

What's going on here?

like image 268
Martin Burch Avatar asked Dec 05 '14 00:12

Martin Burch


People also ask

Do indexes need to be unique?

index: if it's not primary or unique, it doesn't constrain values inserted into the table, but it does allow them to be looked up more efficiently.

What qualifies as a unique index?

Unique indexes are indexes that help maintain data integrity by ensuring that no rows of data in a table have identical key values. When you create a unique index for an existing table with data, values in the columns or expressions that comprise the index key are checked for uniqueness.

Is unique index faster Postgres?

As for speed - unique should be faster - when index scanning finds row with given value, it doesn't have to search if there are any other rows with this value, and can finish scanning imemdiately.


1 Answers

Indexes and tables (and views, and sequences, and...) are stored in the pg_class catalog, and they're unique per schema due to a unique key on it:

# \d pg_class       Table "pg_catalog.pg_class"      Column     |   Type    | Modifiers  ----------------+-----------+-----------  relname        | name      | not null  relnamespace   | oid       | not null  ... Indexes:     "pg_class_oid_index" UNIQUE, btree (oid)     "pg_class_relname_nsp_index" UNIQUE, btree (relname, relnamespace) 

Per @wildplasser's comment, you can omit the name when creating the index, and PG will assign a unique name automatically.

like image 152
Denis de Bernardy Avatar answered Oct 26 '22 16:10

Denis de Bernardy