As far I know the only way of dropping primary key in postgresql is:
ALTER TABLE schema.tableName DROP CONSTRAINT constraint_name;
the constraint name by default is tableName_pkey
. However sometimes if table is already renamed I can’t get the original table name to construct right constraint name.
For example, for a table created as A
then renamed to B
the constraint remains A_pkey
but I only have the table name B
.
Do you know right way to drop the pkey constraint by knowing only the schema name and table name ?
I am writing program for doing this so I need to use only SQL queries. Solutions like "open pgAdmin and see the constraint name" will not work.
3条答案
按热度按时间huus2vyu1#
You can use information from the catalog tables like so:
Create a table with id as the primary key
Create the SQL to drop the key
The result will be:
You can create a stored function to extract this query and then
execute
it.zhte4eai2#
login to the database using psql, the command line tool.
Then type:
for example:
This shows you the primary key name (as well as other stuff).
If you want to do this programmatically and you are using Java or another language that uses the JDBC interface, you can use the class DatabaseMetaData, method getPrimaryKeys.
Otherwise, the other answer, selecting from the system catalogs, is the way to go.
hkmswyz63#
对于使用PGAdmin的用户:导航到数据库〉模式〉{您的模式}〉表〉{您的表名}右键单击〉属性。转到约束选项卡并随意添加/删除。
我使用PGAdmin 4和PostgreSQL 14完成了这一操作。