When I first started using PostgreSQL on Ubuntu, I was confused by this command:
sudo -u postgres psql
It worked — but I didn't fully understand why. Here's what's really happening.
sudo → run a command as another Linux user-u postgres → run as the Linux user postgres
psql → start the PostgreSQL client programOn Ubuntu, PostgreSQL sets up three things by default:
postgrespostgrespostgresBecause all three share the same name, PostgreSQL can safely assume:
postgrespostgresSo when I run: sudo -u postgres psql
PostgreSQL automatically connects me as:
postgrespostgresThat's why no username or database name is required.
Once inside psql, I ran:
\c longlist
The prompt changed from:
postgres=#
to
longlist=#
This means:
I am still logged in as the postgres role. Only the database
changed — not the user.
\c is a psql meta-command.
\c longlist
It means: Disconnect from the current database and connect to
longlist
using the same role.