2

I want to truncate the whole database while maintaining the sequence identity. I came up with something like this:

WITH tables_to_be_truncated AS (
SELECT table_name
    FROM information_schema.tables
    WHERE table_type='BASE TABLE'
    AND table_schema='public'
    AND table_name NOT IN ('admins', 'admin_roles')
)
TRUNCATE TABLE (SELECT table_name FROM tables_to_be_truncated) CONTINUE IDENTITY RESTRICT;

I get this error:

ERROR:  syntax error at or near "TRUNCATE"
LINE 9: TRUNCATE TABLE (SELECT table_name FROM tables_to_be_truncated...

I do have the permissions to truncate the tables and when I run for a single table like TRUNCATE TABLE access_tokens it works fine.

I also tried with this

TRUNCATE TABLE (SELECT string_agg(table_name, ', ') FROM tables_to_be_truncated) CONTINUE IDENTITY RESTRICT

which didn't work as well.

From what I see in other posts, people are doing it with functions. I didn't want to go down this path honestly but if this is the only way...

1
  • 2
    You need dynamic SQL for this. TRUNCATE syntax supports only a static list of table names, not a query. Commented Jul 27, 2021 at 14:17

1 Answer 1

6

You don't need a function for that. An anonymous code block will do:

DO $$
DECLARE row RECORD;
BEGIN
  FOR row IN SELECT table_name
    FROM information_schema.tables
    WHERE table_type='BASE TABLE'
    AND table_schema='public'
    AND table_name NOT IN ('admins', 'admin_roles') 
  LOOP 
    EXECUTE format('TRUNCATE TABLE %I CONTINUE IDENTITY RESTRICT;',row.table_name);
  END LOOP;
END;
$$;

Other than that I don't think you'll be able to run dynamic queries with pure SQL.

Demo: db<>fiddle

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

3 Comments

amazing! that is what I was looking for. Thanks!
yeah, just did, couldn't accept earlier because of the SO cooldown :)
@LuizE. no problem.. happy coding :)

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.