Postgres (SQL) - Create database using the createdb or psql command
by
Jeremy Canfield |
Updated: August 15 2023
| Postgres (SQL) articles
The which command can be used to determine if the createdb command is in your $PATH.
~]$ which createdb
/usr/bin/createdb
If using the default posgres user account, I typically go with the following command. In this example, a database named "mydb" is created.
sudo -u postgres createdb mydb
If you have created a user account, the -u or --username option and --password flag can be used.
createdb --username johndoe --password mydb
Better yet, you can setup passwordless authentication using the hidden .pgpass file and then connect without the --password flag. In this scenario, you would need to be in johndoe home directory since the hidden .pgpass file should be in johndoe home directory.
~] cd /home/johndoe
~] psql --username johndoe --dbname mydb createdb mydb
Or, the --command option can be used.
~] cd /home/johndoe
~] psql --username johndoe --dbname mydb --command "create database mydb"
Or you could set the PGPASSWORD environment variable.
~] export PGPASSWORD='itsasecret'
~] psql --username johndoe --dbname mydb --command "create database mydb"
~] unset PGPASSWORD
Did you find this article helpful?
If so, consider buying me a coffee over at