Manage users in PostgreSQL by creating, altering, granting, and revoking roles to control database access and security.
PostgreSQL treats users as roles with optional login. Proper role management secures data and enforces least-privilege access for every engineer and service touching your ecommerce database.
Run CREATE ROLE
with LOGIN
and a password. The user is created instantly and can connect if the role has CONNECT rights on the target database.
CREATE ROLE storefront_reader LOGIN PASSWORD 'TempP@ss123';
First, add the role to a read-only group. Then grant USAGE on schema and SELECT on tables.This avoids repeating grants for each new table.
-- group role
.
authreader=# CREATE ROLE readonly;
-- membership
authreader=# GRANT readonly TO storefront_reader;
-- permissions
appdb=# GRANT USAGE ON SCHEMA public TO readonly;
appdb=# GRANT SELECT ON ALL TABLES IN SCHEMA public TO readonly;
appdb=# ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT SELECT ON TABLES TO readonly;
Use ALTER ROLE ... PASSWORD
. To force reconnection, REVOKE the old connection first or set a short password validity window.
ALTER ROLE storefront_reader PASSWORD 'N3wS3cur3P@ss';
Before dropping a role, reassign or drop its owned objects and revoke memberships. This prevents orphaned privileges.
REASSIGN OWNED BY storefront_reader TO admin;
DROP OWNED BY storefront_reader;
DROP ROLE storefront_reader;
Prefer group roles, avoid superuser grants, rotate passwords, and audit role memberships quarterly. Automate with migration scripts so changes are version-controlled.
Yes. Use CREATE ROLE ... CONNECTION LIMIT n
to cap concurrent sessions and protect the server from overload.
Query pg_roles
or run \du
in psql to view every role, its attributes, and memberships.
Set VALID UNTIL 'YYYY-MM-DD'
when creating or altering a role. Login fails after the timestamp until the password is reset.