Postgres - How to use psql to create a database with the -c command and password authentication?

If I run the following:

psql -h localhost -U admin -c "CREATE DATABASE sales OWNER admin;"

It returns:

psql FATAL: database "admin" does not exist

I need to use password authentication and have setup .pgpass as follows:

localhost:*:*:admin:admin

Any ideas?

Answers


By default, when you connect as a user, the database connected to is the DB of the same name as the user.

If you want to connect to a different DB, you must specify it in the psql command line. Since in this case you're trying to create the DB, you can't connect to it yet, you must connect to another DB (like template1 or postgres) that already exists.

E.g.

psql -h localhost -U admin template1 -c "CREATE DATABASE sales OWNER admin;"
                           ^^^^^^^^^

Need Your Help

Not getting all the results

elasticsearch

This is my question related to my previous question that I asked search stops after the first match