Skip to content

Instantly share code, notes, and snippets.

@oleg-koval
Created February 23, 2018 13:54
Show Gist options
  • Save oleg-koval/e3e1dd4aecc728955869d115dd176203 to your computer and use it in GitHub Desktop.
Save oleg-koval/e3e1dd4aecc728955869d115dd176203 to your computer and use it in GitHub Desktop.
Truncating all tables in a Postgres database
CREATE OR REPLACE FUNCTION truncate_tables(username IN VARCHAR) RETURNS void AS $$
DECLARE
statements CURSOR FOR
SELECT tablename FROM pg_tables
WHERE tableowner = username AND schemaname = 'public';
BEGIN
FOR stmt IN statements LOOP
EXECUTE 'TRUNCATE TABLE ' || quote_ident(stmt.tablename) || ' CASCADE;';
END LOOP;
END;
$$ LANGUAGE plpgsql;
select public.truncate_tables(
:username -- put the username parameter value instead of 'username' (varchar)
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment