Roles, Grants & Row-Level Security
Lesson opener
In one line: Roles vs “users” in Postgres (spoiler: users are roles that can log in).
Why it matters: This shows up at work when you need to roles vs “users” in Postgres (spoiler: users are roles that can log in).
Before this lesson: SQL & DBMS (MySQL) / Postgres orientation / EXPLAIN
Before you start
| Resource | Link |
|---|---|
| Previous | EXPLAIN & query planning |
| Next | Backup, restore & operational basics |
| Prerequisites | SQL & DBMS (MySQL) foundation; Postgres orientation through EXPLAIN — you should already be comfortable creating tables and running SQL in psql |
| Time | ~50 minutes |
What you will learn
- Roles vs “users” in Postgres (spoiler: users are roles that can log in)
GRANT/REVOKEon tables and columns at a practical level- Row-level security (RLS) — policies that limit which rows a role can see
- A minimal pattern for read-only analyst access
Roles in one minute
CREATE ROLE analyst NOINHERIT LOGIN PASSWORD 'change-me-in-real-life';
CREATE ROLE reporting NOLOGIN;
GRANT reporting TO analyst;Breaking it down:
LOGIN→ can connect (often called a “user”)NOLOGIN→ group/role for bundling privileges- Prefer granting rights to a group role, then grant membership to people
NOINHERIT→ membership alone is not enough (see next block)
In managed cloud Postgres you may use IAM instead of passwords — the privilege ideas stay the same.
Why NOINHERIT means you must SET ROLE
analyst is a member of reporting, but with NOINHERIT those group privileges do not apply automatically when you connect as analyst.
You must run:
SET ROLE reporting;…before queries that rely on grants made to reporting. Then (optionally) RESET ROLE; to drop back to only analyst’s own privileges.
This is deliberate: it stops silent privilege creep if someone is added to a powerful group. It is not optional for the table/view checks below — skip SET ROLE and you get permission denied even though GRANT reporting TO analyst succeeded.
Keep NOINHERIT in this lab. Do not “fix” the confusing error by switching the role to INHERIT.
Table privileges
[Read-only access to analytics tables]
As a privileged role (owner/superuser), grant to the group:
GRANT USAGE ON SCHEMA public TO reporting;
GRANT SELECT ON customers, sales TO reporting;
-- future tables:
ALTER DEFAULT PRIVILEGES IN SCHEMA public
GRANT SELECT ON TABLES TO reporting;Column-level (when needed):
REVOKE SELECT ON customers FROM reporting;
GRANT SELECT (customer_id, segment, total_revenue) ON customers TO reporting;Writers need INSERT/UPDATE/DELETE deliberately — do not hand out ALL on production schemas to analysts.
Prove it as analyst (required SET ROLE): connect as analyst, then:
-- Required: activate the reporting group privileges (NOINHERIT)
SET ROLE reporting;
SELECT customer_id, segment, total_revenue
FROM customers
LIMIT 5;
SELECT COUNT(*) FROM sales;
RESET ROLE; -- back to analyst-only privilegesWithout SET ROLE reporting;, those SELECTs fail with permission denied — that is expected with NOINHERIT, not a broken grant.
Row-level security — the idea
RLS attaches policies to a table. Even with SELECT privilege, rows failing the policy disappear (or reject writes).
[Tenant-style isolation on a simplistic app table]
CREATE TABLE app_orders (
order_id TEXT PRIMARY KEY,
tenant_id TEXT NOT NULL,
amount NUMERIC(12,2) NOT NULL
);
ALTER TABLE app_orders ENABLE ROW LEVEL SECURITY;
CREATE POLICY tenant_select ON app_orders
FOR SELECT
USING (tenant_id = current_setting('app.tenant_id', true));
CREATE POLICY tenant_write ON app_orders
FOR ALL
USING (tenant_id = current_setting('app.tenant_id', true))
WITH CHECK (tenant_id = current_setting('app.tenant_id', true));Session sets the tenant (application does this after auth):
SELECT set_config('app.tenant_id', 'acme', false);
SELECT * FROM app_orders; -- only acme rowsBreaking it down:
ENABLE ROW LEVEL SECURITY→ turn the mechanism onUSING→ which existing rows are visible / updatableWITH CHECK→ which new/updated row images are allowed- Table owners and superusers bypass RLS unless
FORCE ROW LEVEL SECURITY
BYPASSRLS and owners
BYPASSRLS means “this role ignores row-level security policies” — every row stays visible even when RLS is on, so you never see what a normal user would see.
Superusers and roles with BYPASSRLS skip policies. For demos, use a non-owner login role to see RLS work. In production, migrations often run as owner — apps connect as constrained roles.
Practical analyst pattern
- Group role
reportingwithSELECTon curated schemas/views. - Expose views that already hide sensitive columns.
- Add RLS when one table serves many tenants/org units.
- Never share the table-owner password with BI tools.
CREATE VIEW customers_public AS
SELECT customer_id, segment, total_revenue, churned
FROM customers;
GRANT SELECT ON customers_public TO reporting;Prove the view as analyst (required SET ROLE):
SET ROLE reporting;
SELECT * FROM customers_public LIMIT 5;
RESET ROLE;Again: the grant targets reporting. With NOINHERIT, analyst must SET ROLE reporting first.
Essential commands
| Command / action | What it does |
|---|---|
CREATE ROLE … LOGIN | Login-capable role |
GRANT SELECT ON … | Read privilege |
SET ROLE group_role / RESET ROLE | Activate / drop group privileges when membership is NOINHERIT |
ENABLE ROW LEVEL SECURITY | Activate RLS on a table |
CREATE POLICY … | Row filter / check rules |
set_config('app…', …) | Session setting for policies |
Practice
Do this now (on a local throwaway DB):
- Create a
reportinggroup role and ananalystlogin role withNOINHERIT(as in the lesson). GRANT SELECToncustomers/sales(and/orcustomers_public) toreporting.- Connect as
analyst. RunSET ROLE reporting;(required), then confirm you canSELECTthe allowed columns / view. RunRESET ROLE;afterward. - Create a small
app_orderstable, enable RLS, add a policy using a session setting. Grant whateverapp_ordersaccess the demo needs directly toanalyst(not only viareporting). For this RLS check you do not needSET ROLE reporting— connect asanalyst, setapp.tenant_id, and confirm you only see allowed rows. - Save the SQL as
exercises/answers/pg/09_roles_rls.sql.
Teacher walkthrough: least privilege + RLS mindset
All figures illustrative.
Steps: Create a read-only role; GRANT selectively; sketch one RLS policy for tenant isolation (lab only).
Failure example
Symptom: App used superuser connection string
Diagnosis: Convenience over least privilege; RLS bypassed by table owner patterns.
Correction: App role with minimal grants; test as that role; enable RLS carefully per docs.
Validation: Re-run the lesson's verify query/EXPLAIN snippet and confirm expected plan or result.
Guided practice
Does GRANT CONNECT on database imply table SELECT?
Complete solution: No — database connect ≠ table privilege; grant per object (or via schema usage + table grants).
Independent practice
Acceptance criteria:
- Completed the lesson's practice queries on your lab database.
- One failure you hit (or a simulated one) documented with fix.
- Notes state when not to use this feature.
- Link forward to the next
pglesson.
Common mistakes
- Copying MySQL dialect unchanged.
- Skipping
EXPLAINwhen performance is the claim. - Changing production without a transaction/backup habit (pg10).
Checklist
- [ ] I can explain role vs login role
- [ ] I understand why
NOINHERITmeansSET ROLEis required before group grants apply - [ ] I granted least-privilege
SELECTrather than superuser access - [ ] I enabled RLS and saw a policy filter rows
- [ ] Next: Backup, restore & operational basics