Connect to PostgreSQL – How to Connect to psql and Run SQL Commands from Command Line

command linepostgresqlpsql

I'm trying to write a quick line in bash that will use psql to connect to a database and delete all entries in two tables:

\connect some_db
DELETE from some_table
DELETE from another_table

I'd like to do this in one line of bash scripting like so:

psql -U <username> -c "\c some_db; DELETE from some_table; DELETE from another_table"

but it seems like I can't do that because the \c command creates a new context that the subsequent commands don't apply towards.

What's the right way to do this in a line or two from the CLI?

Best Answer

You don't need the \c in the command specified with -c, you can specify the database as a parameter to psql:

psql -U <username> -d some_db -c "DELETE from some_table; DELETE from another_table"