Rana Maninder Singh
Lesson 9 of 11PostgreSQL

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

ResourceLink
PreviousEXPLAIN & query planning
NextBackup, restore & operational basics
PrerequisitesSQL & 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 / REVOKE on 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:

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 privileges

Without 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 rows

Breaking it down:


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

  1. Group role reporting with SELECT on curated schemas/views.
  2. Expose views that already hide sensitive columns.
  3. Add RLS when one table serves many tenants/org units.
  4. 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 / actionWhat it does
CREATE ROLE … LOGINLogin-capable role
GRANT SELECT ON …Read privilege
SET ROLE group_role / RESET ROLEActivate / drop group privileges when membership is NOINHERIT
ENABLE ROW LEVEL SECURITYActivate 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):

  1. Create a reporting group role and an analyst login role with NOINHERIT (as in the lesson).
  2. GRANT SELECT on customers / sales (and/or customers_public) to reporting.
  3. Connect as analyst. Run SET ROLE reporting; (required), then confirm you can SELECT the allowed columns / view. Run RESET ROLE; afterward.
  4. Create a small app_orders table, enable RLS, add a policy using a session setting. Grant whatever app_orders access the demo needs directly to analyst (not only via reporting). For this RLS check you do not need SET ROLE reporting — connect as analyst, set app.tenant_id, and confirm you only see allowed rows.
  5. 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:

Common mistakes

  1. Copying MySQL dialect unchanged.
  2. Skipping EXPLAIN when performance is the claim.
  3. Changing production without a transaction/backup habit (pg10).

Checklist

  • [ ] I can explain role vs login role
  • [ ] I understand why NOINHERIT means SET ROLE is required before group grants apply
  • [ ] I granted least-privilege SELECT rather than superuser access
  • [ ] I enabled RLS and saw a policy filter rows
  • [ ] Next: Backup, restore & operational basics