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

跟風遠走 提交于 2020-02-01 10:07:29

问题


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?


回答1:


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.




回答2:


  • Names are unique within the schema. A schema is basically a namespace for {tables,constraints}, (and indexes, functions,etc).
  • cross-schema-constraints are allowed
  • Indexes share their namespace ( :=schema) with tables. (for Postgres: an index is a table).
  • (IIRC) the SQL standard does not define indexes; use constraints whenever you can (The GIST index in the question is probably an exception)
  • Ergo You'll need to invent another name.
  • or omit it: the system can invent a name if you dont supply one.
  • The downside of this: you can create multipe indices with the same definition (their names will be suffixed with _1, _2, IIRC)


来源:https://stackoverflow.com/questions/27306539/at-what-level-do-postgres-index-names-need-to-be-unique

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!