Learn how to create roles and users in PostgreSQL with login privileges, passwords, and permission management. Includes practical examples and CREATE ROLE syntax.
In PostgreSQL, a role is a central concept for managing users and permissions.
A role is an entity that can:
π In simple words: Role = User + Permissions system
There are mainly two types:
student1, adminRoles are used for security and management:
CREATE ROLE role_name;
CREATE ROLE student1
WITH LOGIN
PASSWORD '1234';
CREATE ROLE teacher
WITH
LOGIN
PASSWORD 'securepass'
CREATEDB
CREATEROLE;
| Option | Meaning |
|---|---|
| LOGIN | Can log in (makes it a user) |
| PASSWORD | Set password |
| CREATEDB | Can create databases |
| CREATEROLE | Can create roles |
| SUPERUSER | Full access (admin) |
| NOSUPERUSER | Normal user |
CREATE ROLE admin_user
WITH LOGIN
PASSWORD 'admin123'
SUPERUSER;
GRANT teacher TO student1;
Students will:
Before assigning ownership, the role must exist.
CREATE ROLE senior_admin
WITH LOGIN
PASSWORD 'secure_pass123';
LOGIN β makes it a userLOGIN β it is just a group roleπ Key Idea: In PostgreSQL, there is no separate βuserβ concept β everything is a role
SELECT rolname FROM pg_roles;
βοΈ This retrieves all roles in the server.
pg_rolesStores:
SELECT
rolname,
rolsuper,
rolcreaterole,
rolcreatedb,
rolcanlogin
FROM pg_roles;
| Column | Meaning |
|---|---|
| rolname | Role name |
| rolsuper | Superuser or not |
| rolcreaterole | Can create roles |
| rolcreatedb | Can create DB |
| rolcanlogin | Can login |
SELECT rolname
FROM pg_roles
WHERE rolcanlogin = true;
\du
ALTER DATABASE dvdrental OWNER TO senior_admin;
Ownership is very powerful:
Owner can:
π Ownership β Normal permissions
After running:
ALTER DATABASE dvdrental OWNER TO senior_admin;
βοΈ Only the database owner changes
β Tables like:
filmactorcustomerπ DO NOT change owner automatically
In terminal:
\l
| Database | Owner |
|---|---|
| dvdrental | senior_admin |
Only:
π can run ALTER DATABASE
Otherwise:
β permission denied