Skip to content

Instantly share code, notes, and snippets.

@bsitruk
Created July 5, 2017 13:57
Show Gist options
  • Save bsitruk/a4bb140543b12f6f3708bc38df5d8cc3 to your computer and use it in GitHub Desktop.
Save bsitruk/a4bb140543b12f6f3708bc38df5d8cc3 to your computer and use it in GitHub Desktop.
PostgreSQL function: Remove all data from the db's tables, and restart id sequences.
DECLARE
statements CURSOR FOR
SELECT tablename FROM pg_tables
WHERE schemaname = 'public';
BEGIN
FOR stmt IN statements LOOP
EXECUTE 'TRUNCATE TABLE ' || quote_ident(stmt.tablename) || ' CASCADE;';
EXECUTE 'ALTER SEQUENCE ' || quote_ident('' || stmt.tablename || '_id_seq') || ' RESTART WITH 1';
END LOOP;
END;
$$ LANGUAGE plpgsql;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment