PostgreSQL Beginner Confusion: What does `sudo -u postgres psql` Means?

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.

Breaking down the command

Why this works on Ubuntu

On Ubuntu, PostgreSQL sets up three things by default:

  1. A Linux user named postgres
  2. A PostgreSQL role named postgres
  3. A PostgreSQL database named postgres

Because all three share the same name, PostgreSQL can safely assume:

So when I run: sudo -u postgres psql

PostgreSQL automatically connects me as:

That's why no username or database name is required.

Switching databases inside psql

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.

What is \c? (Simple explanation)

\c is a psql meta-command.

\c longlist

It means: Disconnect from the current database and connect to longlist using the same role.