Postgres检索约束的名称

时间:2016-01-22 17:18:59

标签: postgresql primary-key alter-table

如何查看约束的名称?

例如:

ALTER TABLE contractor_contractor ADD CONSTRAINT commerce_contractor_pkey  PRIMARY KEY(id);

当我尝试使用\d描述我的表格时,我看不到有关主键的任何信息。

1 个答案:

答案 0 :(得分:1)

您可以从信息架构中查询约束名称:

SELECT constraint_name
FROM   information_schema.table_constraints
WHERE  table_catalog = 'my_catalog_name' AND    -- Database name
       table_schema = 'my_schema_name' AND      -- Often "public"
       table_name = 'contractor_contractor' AND 
       constraint_type = 'PRIMARY KEY';

另请注意,较新版本的plsql确实提供了有关索引部分下主键的信息。 E.g:

db=> CREATE TABLE contractor_contractor (id INT);
CREATE TABLE
db=> ALTER TABLE contractor_contractor
db-> ADD CONSTRAINT commerce_contractor_pkey  PRIMARY KEY(id);
ALTER TABLE
db=> \d contractor_contractor 
Table "public.contractor_contractor"
 Column |  Type   | Modifiers 
--------+---------+-----------
 id     | integer | not null
Indexes:
    "commerce_contractor_pkey" PRIMARY KEY, btree (id)