AI Hints
Home›PostgreSQL Tutorial›Roles, Privileges and Row-Level Security
PostgreSQL · Lesson 79 of 120

Roles and Privileges

Who can do what.

⏱ 2 min read▶ Video at 1:11:05🎓 Free
Watch this lesson in the PostgreSQL courseWatch on YouTube ↗Full PostgreSQL course

The reporting tool should read data, but never change it. In Postgres, users and groups are both called roles, and grant gives each role exactly the access it needs.

  • Read only
  • Never change
  • GRANT

A read only role

Create role makes a login role called reporter. Grant select lets it read the books table. Set role switches to it, so we can test. Run it. Reading works, but the update is denied.

query.sqlsql
CREATE ROLE reporter LOGIN PASSWORD 'secret';
GRANT SELECT ON books TO reporter;

SET ROLE reporter;
SELECT count(*) FROM books;
UPDATE books SET price = 1 WHERE book_id = 1;
Output
CREATE ROLE
GRANT
SET
 count
-------
    30
(1 row)

ERROR:  permission denied for table books

Privilege tips

Grant to group roles, then add users to groups. Give the least access that works. Revoke takes access away. And default privileges apply grants to tables created later.

keyvalue
Group rolesGRANT role TO user
Least privilegeonly what's needed
REVOKEtake away
ALTER DEFAULT PRIVILEGESfuture tables

Summary

Roles are users and groups, and grant and revoke control what each can do. Next, security for individual rows.

Key takeaways
  • CREATE ROLE
  • GRANT
  • REVOKE
Next up: Row-Level Security — each sees their own rows