Change tables, manage access, and create views
PostgreSQL 19.0
Use the school tables from Setup in learning_db. Each example runs in its own transaction and rolls back at the end so you can repeat it.
On this page
Add a column with ALTER TABLE
Add room_code to courses, fill it for SQL Basics, and read the result. ROLLBACK returns the table to its original structure.
BEGIN;
ALTER TABLE courses ADD COLUMN room_code text;
UPDATE courses SET room_code = 'A-01' WHERE id = 1;
SELECT title, room_code FROM courses ORDER BY id;
ROLLBACK;
Grant and revoke read access
Run as the practice table owner with permission to create roles. The temporary role has no login. With default table permissions, the privilege check returns true after GRANT and false after REVOKE. ROLLBACK removes the temporary role too.
BEGIN;
CREATE ROLE lesson_course_reader NOLOGIN;
GRANT USAGE ON SCHEMA public TO lesson_course_reader;
GRANT SELECT ON TABLE public.courses TO lesson_course_reader;
SELECT has_table_privilege('lesson_course_reader', 'public.courses', 'SELECT');
REVOKE SELECT ON TABLE public.courses FROM lesson_course_reader;
SELECT has_table_privilege('lesson_course_reader', 'public.courses', 'SELECT');
ROLLBACK;
Read course enrollment totals through a view
A view gives a query a reusable name. This view reads the underlying tables each time you query it. It includes courses with no enrollments.
BEGIN;
CREATE VIEW lesson_course_enrollments AS
SELECT c.id, c.title, COUNT(e.student_id) AS student_count
FROM courses AS c
LEFT JOIN enrollments AS e ON e.course_id = c.id
GROUP BY c.id, c.title;
SELECT title, student_count FROM lesson_course_enrollments
ORDER BY student_count DESC, id;
ROLLBACK;