Postgre SQL
Postgre SQL
Prerequisites
To follow along with this tutorial, you will need one Ubuntu 22.04 server that has been configured
by following our Initial Server Setup for Ubuntu 22.04 guide. After completing this prerequisite
tutorial, your server should have a non-root user with sudo permissions and a basic firewall.
Then, install the Postgres package along with a -contrib package that adds some additional
utilities and functionality:
sudo apt install postgresql postgresql-contrib
Press Y when prompted to confirm installation. If you are prompted to restart any services,
press ENTER to accept the defaults and continue.
This will bring you back to the postgres Linux command prompt. To return to your regular system
user, run the exit command:
exit
Another way to connect to the Postgres prompt is to run the psql command as the postgres
account directly with sudo:
sudo -u postgres psql
This will log you directly into Postgres without the intermediary bash shell in between.
Again, you can exit the interactive Postgres session by running the following:
\q
If, instead, you prefer to use sudo for each command without switching from your normal account,
run:
sudo -u postgres createuser --interactive
Either way, the script will prompt you with some choices and, based on your responses, execute the
correct Postgres commands to create a user to your specifications.
Output
Enter name of role to add: sammy
Shall the new role be a superuser? (y/n) y
If you are logged in as the postgres account, you would type something like the following:
createdb sammy
If, instead, you prefer to use sudo for each command without switching from your normal account,
you would run:
sudo -u postgres createdb sammy
Once this new account is available, you can either switch over and connect to the database by
running the following:
sudo -i -u sammy
psql
This command will log you in automatically, assuming that all of the components have been
properly configured.
If you want your user to connect to a different database, you can do so by specifying the database
like the following:
psql -d postgres
Once logged in, you can get check your current connection information by running:
\conninfo
Output
You are connected to database "sammy" as user "sammy" via socket in
"/var/run/postgr