Received: from malur.postgresql.org ([217.196.149.56]) by arkaria.postgresql.org with esmtps (TLS1.3:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.92) (envelope-from ) id 1looBw-0006B2-8n for pgsql-general@arkaria.postgresql.org; Thu, 03 Jun 2021 14:19:24 +0000 Received: from localhost ([127.0.0.1] helo=malur.postgresql.org) by malur.postgresql.org with esmtp (Exim 4.92) (envelope-from ) id 1looBP-0004iM-S2 for pgsql-general@arkaria.postgresql.org; Thu, 03 Jun 2021 14:18:51 +0000 Received: from makus.postgresql.org ([2001:4800:3e1:1::229]) by malur.postgresql.org with esmtps (TLS1.3:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.92) (envelope-from ) id 1looBP-0004iE-It for pgsql-general@lists.postgresql.org; Thu, 03 Jun 2021 14:18:51 +0000 Received: from sss.pgh.pa.us ([66.207.139.130]) by makus.postgresql.org with esmtps (TLS1.3:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.92) (envelope-from ) id 1looBJ-0003tX-GP for pgsql-general@lists.postgresql.org; Thu, 03 Jun 2021 14:18:50 +0000 Received: from sss1.sss.pgh.pa.us (localhost [127.0.0.1]) by sss.pgh.pa.us (8.15.2/8.15.2) with ESMTP id 153EIhMC273407; Thu, 3 Jun 2021 10:18:44 -0400 From: Tom Lane To: Tiffany Thang cc: "pgsql-generallists.postgresql.org" Subject: Re: Dropping dependent tables In-reply-to: References: Comments: In-reply-to Tiffany Thang message dated "Thu, 03 Jun 2021 09:41:53 -0400" MIME-Version: 1.0 Content-Type: text/plain; charset="UTF-8" Content-ID: <273405.1622729923.1@sss.pgh.pa.us> Content-Transfer-Encoding: 8bit Date: Thu, 03 Jun 2021 10:18:43 -0400 Message-ID: <273406.1622729923@sss.pgh.pa.us> List-Id: List-Help: List-Subscribe: List-Post: List-Owner: List-Archive: Archived-At: Precedence: bulk Tiffany Thang writes: > I would like to write a SQL statement to drop all the tables owned by me > but a problem I’m struggling with is with referential integrity. The > statement I have now to generate the drop statements is > select 'drop table '||tablename||' cascade;' from pg_tables where > tableowner=''; > The generated SQLs above might attempt to drop the parent tables first > before the child and to be able to drop all the tables, I had to run the > SQL script in multiple iterations. Not very clean. Uh ... it's not clear to me why that wouldn't work. CASCADE should be able to take care of foreign keys: postgres=# create table t1 (f1 int primary key); CREATE TABLE postgres=# create table t2 (f2 int references t1); CREATE TABLE postgres=# drop table t1; ERROR: cannot drop table t1 because other objects depend on it DETAIL: constraint t2_f2_fkey on table t2 depends on table t1 HINT: Use DROP ... CASCADE to drop the dependent objects too. postgres=# drop table t1 cascade; NOTICE: drop cascades to constraint t2_f2_fkey on table t2 DROP TABLE Could you enlarge on what problem you saw, specifically? regards, tom lane