Postgres索引名称在什么级别需要是唯一的?

Mar*_*rch 16 postgresql indexing

Microsoft SQL Server和MySQL中,索引名称需要在表中唯一,但不在数据库中.这似乎不是PostgreSQL的情况.

这就是我正在做的事情:我使用CREATE TABLE new_table AS SELECT * FROM old_tableetc 制作了一个表的副本,需要重新创建索引.

CREATE INDEX idx_column_name ON new_table USING GIST(column_name)原因一样运行查询ERROR: relation "idx_column_name" already exists

这里发生了什么?

Den*_*rdy 21

索引和表(以及视图,序列和...)存储在pg_class目录中,由于其上有唯一的键,它们对于每个模式都是唯一的:

# \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)
Run Code Online (Sandbox Code Playgroud)

Per @ wildplasser的注释,您可以在创建索引时省略名称,PG将自动分配唯一的名称.


wil*_*ser 5

  • 名称在架构中是唯一的.模式基本上是{tables,constraints},(以及索引,函数等)的命名空间.
  • 允许跨架构约束
  • 索引与表共享其命名空间(:= schema).(对于Postgres:索引一个表).
  • (IIRC)SQL标准没有定义索引; 尽可能使用约束(问题中的GIST索引可能是一个例外)
  • 你需要发明另一个名字.
  • 或省略它:如果您不提供名称,系统可以创建一个名称.
  • 这种方法的缺点:您可以创建multipe指数具有相同的定义(他们的名字将与后缀_1,_2,IIRC)