How to setup PostgreSQL on MacOS
I would be lying, if I say I don't look up how to setup PostgreSQL - every DAMN time. We know it was hard to do before, but now it isn't, yet most of the guides we find are outdated. So, here we have an updated version of it.
Installing PostgreSQL
First, install HomeBrew if you don't have it already, you can use the following script to install it.
/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"Once you are done with it, update HomeBrew dependencies and install PostgreSQL.
brew update
brew install postgresqlSee, I told you it was Easy. Let's check Postgres version
postgres --version
postgres (PostgreSQL) 11.3Initializing the DB
A Database needs some space allocated on your hard-disk, also called as "cluster" or "Data directory". It happens automatically, but to be sure run the following
initdb /usr/local/var/postgresYou may see the error message: initdb: directory “/usr/local/var/postgres” exists but is not empty if the database was already created when we installed PostgreSQL.
Start/Stop PostgreSQL
You can do it either ways, by directly calling the following
pg_ctl -D /usr/local/var/postgres start
pg_ctl -D /usr/local/var/postgres stopor by using brew
brew services postgres start
brew services postgres stop
brew services postgres restartCreating a PostgreSQL Database
To create a database run the following
createdb databasenameTo remove a database run the following
dropdb databasenameTo Connect to a database run
psql databasenameThis will open up the psql sheel, where you can run SQL quries, to exit press ctrl+d. Some useful commands, to know.
\listTo list all databases.\c databaseNameto connect todatabaseName.\dTo list relations in current database.\d tableNameTo list info of a table.
