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.
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 postgresql
See, I told you it was Easy. Let's check Postgres version
postgres --version postgres (PostgreSQL) 11.3
Initializing 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
You 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.
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 stop
or by using brew
brew services postgres start brew services postgres stop brew services postgres restart
Creating a PostgreSQL Database
To create a database run the following
To remove a database run the following
To Connect to a database run
This 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 to
\dTo list relations in current database.
\d tableNameTo list info of a table.