Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you change a user in PostgreSQL?

postgres=# \du
                         List of roles
Role name |                   Attributes                   | Member of 

-----------+------------------------------------------------+-----------
 postgres  | Superuser, Create role, Create DB, Replication | {}
 shorturl  | Superuser                                      | {}

postgres=# create database shorturl;
CREATE DATABASE

postgres=# \c shorturl;
You are now connected to database "shorturl" as user "postgres".

shorturl=# 

My preference was to use database shorturl being the user shorturl and not postgres. How do I change the same?

Thanks in advance.

like image 448
Abhinav Ralhan Avatar asked May 18 '17 14:05

Abhinav Ralhan


People also ask

How do I login as a different user in PostgreSQL?

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".

How do I see all users in PostgreSQL?

Use \du or \du+ psql command to list all users in the current database server. Use the SELECT statement to query the user information from the pg_catalog.


2 Answers

When you display the psql online help by entering \? you can see:

Connection
  \c[onnect] {[DBNAME|- USER|- HOST|- PORT|-] | conninfo}
                         connect to new database (currently "postgres")

So you need to use:

\c shorturl shorturl
like image 106
a_horse_with_no_name Avatar answered Oct 21 '22 06:10

a_horse_with_no_name


Another option, if you're already connected to database shorturl, is the command:

SET ROLE shorturl;

The benefits of that command are that it's not tied to psql, and that you can change user "midstream" of your work.

like image 2
RonJohn Avatar answered Oct 21 '22 08:10

RonJohn