iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
📦

Checking, Adding, and Dropping Key Constraints in PostgreSQL

に公開

Overview

Recently, I performed a large-scale refactoring of Postgres table definitions.
In the process, I changed column names, but before that, I had to remove constraints such as primary keys and foreign keys, so I am leaving this as a working memo.

Checking Constraints

Constraint information for all tables is stored in table_constraints within information_schema, so you can retrieve the constraints for the target table from there.

Reference: https://www.postgresql.jp/document/8.4/html/infoschema-table-constraints.html

SELECT 
  table_name
  , constraint_name
  , constraint_type
FROM 
  information_schema.table_constraints
WHERE table_name = '<TABLE_NAME>'
    AND (constraint_type = 'PRIMARY KEY' OR constraint_type = 'FOREIGN KEY') ;

Dropping Constraints

DROP the constraint name (CONSTRAINT_NAME) confirmed with the previous query.

ALTER TABLE <TABLE_NAME> DROP CONSTRAINT <CONSTRAINT_NAME>;

By doing this, it becomes possible to operate on the columns that were subject to the constraint.

Creating Constraints

Primary Key

A primary key constraint is added to the column <COLUMN> in TABLE_NAME with an arbitrary name (in this case, CONSTRAINT_NAME).

ALTER TABLE <TABLE_NAME> ADD CONSTRAINT <CONSTRAINT_NAME> PRIMARY KEY(<COLUMN>);

Foreign Key

A foreign key constraint is added to the column <COLUMN> in TABLE_NAME.
The table containing the foreign key (here, FOREIGN_TABLE_NAME) and the column name in that table (here, FOREIGN_COLUMN) are specified.

ALTER TABLE <TABLE_NAME> ADD FOREIGN KEY (<COLUMN>) REFERENCES <FOREIGN_TABLE_NAME> (<FOREIGN_COLUMN>);

Summary

In this post, I have summarized tips for the temporary removal of constraints necessitated by changes in table definitions.
You might encounter this situation once or so in projects where the DB definition has not been finalized in the early stages, or in cases such as personal development, but it is a rare case nonetheless.

I hope this information is helpful.

Discussion