4
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

PostgreSQLで外部キー(FK)をすべて削除する方法

Last updated at Posted at 2016-10-05

環境

  • OS: Windows10
  • PostgreSQL:9.5

FKをすべて削除する方法

データ投入時等で、一旦制約を削除したい場合ってあると思います。
テーブル等が大量にある場合はとても大変な作業です。
一括で削除する方法を紹介します。

SELECT 'ALTER TABLE "'||nspname||'"."'||relname||'" DROP CONSTRAINT "'||conname||'";'
 FROM pg_constraint 
 INNER JOIN pg_class ON conrelid=pg_class.oid 
 INNER JOIN pg_namespace ON pg_namespace.oid=pg_class.relnamespace 
 WHERE contype='f' 
 ORDER BY CASE WHEN contype='f' THEN 0 ELSE 1 END,contype,nspname,relname,conname

補足

以下のコマンドで出力をファイルに変更することができます。

\o [ファイル名]

標準出力に戻す方法は以下を以下を実行するだけです。

\o

参考

Automatically dropping and creating constraints
https://www.hagander.net/blog/automatically-dropping-and-creating-constraints-131/

4
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?