Start by reading the manual on TRUNCATE
for instructions on proper syntax.
Next, you are looking for dynamic SQL, since you cannot use wilcards or patterns for table names in TRUNCATE
. You need to compose the SQL command dynamically. You can do this in two round-trips to the server like has been advised, or you can use a single DO
statement:
DO
$do$
BEGIN
EXECUTE (
-- RAISE NOTICE '%', ( -- better check before you execute ..
SELECT 'TRUNCATE ' || string_agg(c.oid::regclass::text, ', ')
FROM pg_class c
JOIN pg_namespace n ON n.oid = c.relnamespace
WHERE c.relname LIKE 'beach_%'
AND c.relkind = 'r'
AND n.nspname = 'public'
);
END
$do$;
Creates and executes a command of the form:
TRUNCATE beach_foo, beach_bar, ...
You may want to / have to add CASCADE
at the end of the command.
Related answer:
DROP All Views PostgreSQL
Consider the subtle differences between information schema and system catalogs:
How to check if a table exists in a given schema
You may or may not want to query information_schema.tables
instead. Most importantly (per documentation):
Only those tables and views are shown that the current user has access
to (by way of being the owner or having some privilege).
Bold emphasis mine.