To change a PostgreSQL user’s password, use one of the following methods:
Method 1: Using psql (Interactive & Secure)
- Connect to PostgreSQL as a superuser (e.g.,
postgres):
psql -U postgres -d your_database_name
- Change the password with the
\passwordmeta-command:
\password username
You’ll be prompted securely to enter the new password twice.
Example output:
Enter new password for user "username":
Enter it again:
Method 2: Using SQL (Direct Command)
Run the ALTER ROLE SQL command to update the password:
ALTER ROLE username WITH PASSWORD 'new_password';
Notes:
- Replace
usernameandnew_passwordwith actual values. - Security Risk: Avoid exposing passwords in command history or logs. Use this method cautiously.
Optional: Specify Encryption Method
PostgreSQL encrypts passwords by default. To explicitly set the method (e.g., SCRAM-SHA-256):
ALTER ROLE username WITH ENCRYPTED PASSWORD 'new_password';
Key Considerations
- Privileges: You must be a superuser or have
CREATEROLEprivileges to change another user’s password. - Authentication: Ensure
pg_hba.confusesmd5orscram-sha-256for password-based authentication. - Security: Prefer
\passwordinpsqlto avoid exposing plaintext passwords.
Example Workflow
- Connect via
psql:
psql -U postgres
- Change Password:
\password alice
Follow prompts to set a new password for user alice.
Use \password for interactive security or ALTER ROLE in scripts (with caution).