12

I have a schema assigned to my user (jason). I can't remove the schema as I don't have permissions to do so. Is there a nice way to remove each tables, data, everything in a schema and make it as if I had a freshly created schema. Basically the same effect as:

drop schema jason cascade;
create schema jason;

But without the actually dropping the schema.

1
  • I guess the best way would be to generate the list of DROP TABLE statements from the infomration_schema.tables and then run all them at once. Commented Jul 14, 2015 at 12:10

2 Answers 2

18

The accepted answer is great, but you can do this in just one step taking advantage from anonymous blocks (PosgreSQL 9.0+):

DO $$
DECLARE 
    r record;
BEGIN
    FOR r IN SELECT quote_ident(tablename) AS tablename, quote_ident(schemaname) AS schemaname FROM pg_tables WHERE schemaname = 'public'
    LOOP
        RAISE INFO 'Dropping table %.%', r.schemaname, r.tablename;
        EXECUTE format('DROP TABLE IF EXISTS %I.%I CASCADE', r.schemaname, r.tablename);
    END LOOP;
END$$;
Sign up to request clarification or add additional context in comments.

Comments

9

Try this from psql:

-- Turn off headers:
\t
-- Use SQL to build SQL:
select 'drop table if exists "' || tablename || '" cascade;' 
  from pg_tables
 where schemaname = 'jason'; 
-- If the output looks good, write it to a file and run it:
\g out.tmp
\i out.tmp

from stackoverflow.com/questions/3327312/drop-all-tables-in-postgresql

3 Comments

I would also like to comment that this only creates the set of commands that you need to run after this to make delete the table.
Yes and NO, yes create the command set and run they.
Alternative: use \gexec instead of \g & \i

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.