4

Often while adding a feature to an existing project i have something like ( result of listing the databases )

project_x_001, ..., project_x_00n

I need to clean the database at the end, by dropping all the database that start with a certain pattern, in this case project_x_*

is there any elegant ( cleaner ) to do this in PostgreSQL, beside:

drop database project_x_001, ..., project_x_00n;

the list sometimes is too long, and you would need at each time list the databases and delete a chunk of them

4 Answers 4

16

the following solution applies to Ubuntu

for db in `psql -c '\l' | grep project_x_* | cut -d '|' -f 1`; do psql -c "drop database $db"; done

basically the above command loops over the selected databases using grep; please see the result of that selection before dropping anything from the database.

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

1 Comment

Change this to use psql -X to make sure it ignores your .psqlrc custom format - it can mess the grep
2

I needed a slight modification on @rachid's answer because my DB names resulted in an invalid syntax from character: "-"

My DB names where named horribly like testrun-ppsubscriptions-1597745672749-276

So needed to modify it as:

for db in `psql -c '\l' | grep testrun* | cut -d '|' -f 1`; do psql -c "drop database \"$db\" "; done

Thanks @rachid!

Comments

0

That is not possible, see the documentation.

1 Comment

I agree it is not possible using only SQL, i would love to know if there's a hacky way to do it.
0

Use psql gexec:

psql -d postgres://postgres@localhost:5432/postgres <<<"SELECT format( 'ALTER TABLE %I.%I ADD PRIMARY KEY (id);', table_schema, table_name ) FROM information_schema.tables WHERE table_schema = 'my_schema' AND table_type = 'BASE TABLE' \gexec"

Reference: https://dba.stackexchange.com/questions/337469/execute-gexec-in-a-psql-command

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.