How do you connect to PostgreSQL from the command line?

BeginnerHands-onPostgreSQL
Answer

Short answer

Use psql with host, port, user and database: psql -h <host> -p 5432 -U <user> -d <database>, or a connection URL. Locally on Linux, the admin can use sudo -u postgres psql.

Examples

sudo -u postgres psql                                         # local superuser via OS account
psql -h localhost -U postgres                                 # password prompt
psql -h db.prod.internal -p 5432 -U shop_app -d shop
psql "postgresql://[email protected]:5432/shop?sslmode=require"
docker exec -it postgres psql -U postgres -d shop
kubectl exec -it postgres-0 -- psql -U postgres

Avoid typing passwords on the command line

export PGPASSWORD='***'                        # for one script run (visible in env)
echo "db.prod.internal:5432:shop:shop_app:***" >> ~/.pgpass && chmod 600 ~/.pgpass   # better

Running one command or a file

psql -h db -U shop_app -d shop -c "SELECT count(*) FROM orders;"
psql -h db -U shop_app -d shop -f migration.sql -v ON_ERROR_STOP=1

ON_ERROR_STOP=1 makes the script stop (non-zero exit) on the first error — important in pipelines.

What to say in the interview

"psql with -h, -p, -U and -d or a URL with sslmode. For automation I use ~/.pgpass or PGPASSWORD from a secret, -c or -f to run SQL, and ON_ERROR_STOP=1 so failures fail the pipeline."

All Databases (MySQL, PostgreSQL, MongoDB) questions Roadmap: PostgreSQL basics

More on PostgreSQL