Role and Permission Management
Beginner10 min
Create and manage PostgreSQL roles with granular permissions for secure multi-user database access control.
Prerequisites
- -PostgreSQL installed
- -Superuser or admin access to the database
Steps
1
Create a new role with login
Create a database user role with a password and login capability.
$ psql -U postgres -c "CREATE ROLE app_user WITH LOGIN PASSWORD 'secure_password' VALID UNTIL '2027-01-01';"
Always set VALID UNTIL for service accounts to enforce credential rotation.
2
Grant database-level permissions
Allow the role to connect to a specific database.
$ psql -U postgres -c "GRANT CONNECT ON DATABASE mydb TO app_user;"
3
Grant schema and table permissions
Give the role read/write access to tables in a schema.
$ psql -U postgres -d mydb -c "GRANT USAGE ON SCHEMA public TO app_user; GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO app_user;"
4
Set default privileges for future tables
Ensure the role automatically gets permissions on tables created in the future.
$ psql -U postgres -d mydb -c "ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT SELECT, INSERT, UPDATE, DELETE ON TABLES TO app_user;"
5
Create a read-only role
Create a restricted role that can only read data.
$ psql -U postgres -d mydb -c "CREATE ROLE readonly_user WITH LOGIN PASSWORD 'readonly_pass'; GRANT CONNECT ON DATABASE mydb TO readonly_user; GRANT USAGE ON SCHEMA public TO readonly_user; GRANT SELECT ON ALL TABLES IN SCHEMA public TO readonly_user;"
6
List all roles and their attributes
View existing roles with their permissions and settings.
$ psql -U postgres -c "\du+"
Full Script
FAQ
Discussion
Loading comments...