How can I connect to a database as another user?

Here my assumption is you have a SQL file called "a.sql" and contains the lines of code in the file.

CREATE ROLE sa WITH LOGIN PASSWORD 'some-password.';
CREATE DATABASE master WITH OWNER sa;
\c master;

Now you are running this script using "psql" command line interface (CLI), so you get the message as below...

CREATE ROLE
CREATE DATABASE
You are now connected to database "master" as user "postgres".

Now, the thing to be noted that you have connected to database "master" because of "\c master" with user "postgres" because of you passed the credential of "postgres" user. Is I am right here then, If yes, then you have to pass the user and password for different user i.e. "sa" as below.

psql -h localhost -p 5432 -U sa -f a.sql master

Now, it will prompt for the password of "sa" user, finally, your script will run and you will be connected to "sa" user.


You can do this via this command in psql:

\c db_name usr_name

Tags:

Postgresql