How can I change a PostgreSQL user password?

 

To change a PostgreSQL user password, you can use the ALTER USER command. Here's how you can do it:

Assuming you want to change the password for a user named myuser, follow these steps:

  1. Using psql Command Line:

    Start by connecting to your PostgreSQL database using the psql command-line tool:

    sh
  • psql -h <hostname> -U <username> -d <database>

    Replace <hostname>, <username>, and <database> with the appropriate values.

  • Change the Password:

    Once connected to the PostgreSQL shell, you can change the user's password using the ALTER USER command:

    sql
    1. ALTER USER myuser WITH PASSWORD 'newpassword';

      Replace myuser with the username for which you want to change the password, and newpassword with the new password you want to set.

      After executing this command, the user's password will be updated.

    2. Exit the PostgreSQL Shell:

      Exit the PostgreSQL shell by typing \q and pressing Enter.

    Here's an example session:

    sh
    $ psql -h localhost -U postgres -d mydb Password for user postgres: psql (12.8) Type "help" for help. mydb=# ALTER USER myuser WITH PASSWORD 'newpassword'; ALTER ROLE mydb=# \q

    In this example, the PostgreSQL shell is used to change the password for the user myuser in the database mydb. After executing the ALTER USER command, the password is updated, and the user can now use the new password to access the database.

    Keep in mind that you might need appropriate privileges to execute the ALTER USER command. If you're not a superuser, you might need to have the ALTER privilege on the user or have superuser privileges yourself.

    Comments