pg.ddx.io  pgsql-general@postgresql.org mailing list archive  
help / color / mirror / Atom feed
From: Tom Lane <tgl@sss.pgh.pa.us>
To: Tiffany Thang <tiffanythang@gmail.com>
Cc: pgsql-generallists.postgresql.org <pgsql-general@lists.postgresql.org>
Subject: Re: Dropping dependent tables
Date: Thu, 03 Jun 2021 10:18:43 -0400
Message-ID: <273406.1622729923@sss.pgh.pa.us> (raw)
In-Reply-To: <CAB_W-NOtuEuOg=67m_mKyphnWvWRiCR4oSCOVwM14_XE_G-71A@mail.gmail.com>
References: <CAB_W-NOtuEuOg=67m_mKyphnWvWRiCR4oSCOVwM14_XE_G-71A@mail.gmail.com>

Tiffany Thang <tiffanythang@gmail.com> 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='<myuseraccount>';

> 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





view thread (3+ messages)  latest in thread

Message-ID: <273406.1622729923@sss.pgh.pa.us>
Permalink:  ../273406.1622729923@sss.pgh.pa.us/
Also on:    postgresql.org/message-id/273406.1622729923@sss.pgh.pa.us

 · 

reply

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Reply to all the recipients from your mail client; the link fills in
  the headers below: reply via email
  Some clients, webmail especially, drop In-Reply-To and References from
  a link, and the reply then starts a new thread: use the mbox below.

  To: pgsql-general@postgresql.org
  Cc: tgl@sss.pgh.pa.us, tiffanythang@gmail.com
  Subject: Re: Dropping dependent tables
  In-Reply-To: <273406.1622729923@sss.pgh.pa.us>
  References: <CAB_W-NOtuEuOg=67m_mKyphnWvWRiCR4oSCOVwM14_XE_G-71A@mail.gmail.com> <273406.1622729923@sss.pgh.pa.us>

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox