0

I need to remove selected tables from the Postgres SQL. It would better to use like or where clause.

Like I have

TABLE_A
TABLE_B
TABLE_C
-
-
-
TABLE_N

I need to delete

TABLE_A to TABLE_X

2 Answers 2

2

Can be done with a single command, which is faster - in case this is a recurring task.

Add IF EXISTS if the existence of any tables is uncertain. This way we save an extra trip to the system catalogs (information_schema.tables or pg_catalog.pg_tables).
And you may want to add CASCADE:

DO
$do$
BEGIN
  -- child safety device: quote RAISE instead of EXECUTE to prime the bomb
  -- EXECUTE (
  RAISE NOTICE '%', (
     SELECT 'DROP TABLE IF EXISTS'
         || string_agg('table_' || chr(ascii('a') + g) , ', ')
         || ' CASCADE;'
     FROM   generate_series(0,13) g
     );
END
$do$;

Generates a command of the form:

DROP TABLE IF EXISTS table_a, table_b, ... , table_n CASCADE;

Using generate_series() to generate requested table names. More here:

Sign up to request clarification or add additional context in comments.

Comments

1
DO
$$
DECLARE
   r RECORD;
BEGIN
    FOR r IN SELECT oid::REGCLASS table_name
             FROM pg_class
             WHERE relname <= 'table_x'
             AND relkind = 'r'
    LOOP
          EXECUTE 'DROP TABLE' || r.table_name;
    END LOOP;
END;
$$ LANGUAGE plpgsql;

2 Comments

ERROR: missing FROM-clause entry for table "c"
Sorry, I use it with more parameters

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.