Hands-on lab exercise to learn PostgreSQL role management, GRANT and REVOKE permissions, role-based access control with practical examples using admin, teacher, and student roles.
By the end of this lab, students will be able to:
GRANT and REVOKEYou are managing a University Database System with:
CREATE DATABASE university_lab;
Connect to it:
\c university_lab
CREATE TABLE students (
id SERIAL PRIMARY KEY,
name VARCHAR(50),
course VARCHAR(50)
);
Insert sample data:
INSERT INTO students (name, course)
VALUES
('Ali', 'CS'),
('Sara', 'IT'),
('Ahmed', 'SE');
CREATE ROLE admin_user WITH LOGIN PASSWORD 'admin123' SUPERUSER;
CREATE ROLE teacher WITH LOGIN PASSWORD 'teacher123';
CREATE ROLE student WITH LOGIN PASSWORD 'student123';
GRANT SELECT, INSERT ON students TO teacher;
GRANT SELECT ON students TO student;
Switch role:
SET ROLE teacher;
Try:
SELECT * FROM students;
INSERT INTO students (name, course) VALUES ('Zain', 'AI');
Now test student:
SET ROLE student;
Try:
SELECT * FROM students;
INSERT INTO students (name, course) VALUES ('Test', 'CS'); -- Should FAIL
REVOKE INSERT ON students FROM teacher;
Create a new role:
librarian
Create a new table:
books (id, title, author)
Give:
Test access using SET ROLE
Revoke SELECT from student and test again
staff_group