Learn to Code
All tracks
Learn to Code

Free lessons from scratch to pro — every language, databases and DevOps.

AboutContactPrivacy PolicyTerms of Use

Your progress is saved in this browser. © 2026 Learn to Code

PG
PostgreSQL
0/11 completed
Beginner
Why PostgreSQL?psql and your first tablesData types that matter
Intermediate
Constraints and relationshipsPostgres-powered SQLJSONB, arrays and full-text search
Advanced
Views, functions and triggersIndexes and EXPLAINTransactions, MVCC and locking
Pro
Roles, privileges and row-level securityBackups, replication and production
Tracks / PostgreSQL / Pro

Roles, privileges and row-level security

A database is a vault for your most valuable data. PostgreSQL has a precise permission system: who can connect, which tables they can read, which columns they can update, and even which rows they can see.

Roles

In PostgreSQL, users and groups are both roles. A role with LOGIN can connect (a "user"); a role without it is a group you grant permissions to.

PostgreSQL · editable

The postgres role is a superuser: it bypasses every permission check. Never let your application connect as a superuser.

GRANT and REVOKE

New roles can do almost nothing. You grant exactly what's needed, the principle of least privilege:

PostgreSQL · editable

SET ROLE is a quick way to test permissions. Typical grants:

sql
GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO app_user;
GRANT USAGE ON ALL SEQUENCES IN SCHEMA public TO app_user;    -- for serial/identity columns
REVOKE DELETE ON invoices FROM app_user;                      -- invoices can never be deleted by the app

-- Tables created in the future get these privileges too:
ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT SELECT ON TABLES TO readonly;

Column-level privileges

You can grant access to only some columns:

PostgreSQL · editable

Row-level security (RLS)

Grants control tables and columns. Row-level security controls rows: each user sees only the rows a policy allows. It's the foundation of many multi-tenant SaaS apps, where one table holds every company's data.

⚙️ Setup: this runs automatically in every editor below
sql
CREATE TABLE documents (
  id        integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  tenant_id integer NOT NULL,
  title     text NOT NULL
);
INSERT INTO documents (tenant_id, title) VALUES
  (1, 'Acme roadmap'), (1, 'Acme salaries'), (2, 'Globex launch plan'), (3, 'Initech TPS reports');

CREATE ROLE web_app;
GRANT SELECT, INSERT, UPDATE, DELETE ON documents TO web_app;
PostgreSQL · editable

How it works:

  • USING (…) filters which existing rows are visible (for SELECT, UPDATE, DELETE).
  • WITH CHECK (…) validates new or changed rows (INSERT, UPDATE).
  • The app sets app.tenant_id for each request, typically with SET LOCAL inside the request's transaction.
  • With RLS enabled and no matching policy, a role sees nothing: it's deny-by-default.

Even if a developer forgets a WHERE tenant_id = … somewhere, one tenant can never see another's data.

⚠️ Superusers and the table owner bypass RLS (unless you use ALTER TABLE … FORCE ROW LEVEL SECURITY). Make sure the app connects as a separate, non-owner role, as web_app does above.

SQL injection: never build SQL with strings

The most common database vulnerability isn't in Postgres, it's in app code that glues user input into SQL:

js
// ❌ NEVER: user input becomes part of the SQL
const email = req.query.email;                  // attacker sends:  ' OR '1'='1
await db.query(`SELECT * FROM users WHERE email = '${email}'`);
// becomes: SELECT * FROM users WHERE email = '' OR '1'='1'   → returns every user

// ✅ ALWAYS: parameters are sent separately and never parsed as SQL
await db.query('SELECT * FROM users WHERE email = $1', [email]);

Every Postgres driver (node-postgres, psycopg, JDBC…) and ORM supports parameters. Use them, always, even for values you think are safe.

Connection security

  • pg_hba.conf ("host-based authentication") controls which roles can connect from which addresses, and how they authenticate. Allow only your app servers' network.
  • Use scram-sha-256 passwords (the modern default; md5 is deprecated) or certificate auth.
  • Require TLS for connections over a network: sslmode=require or verify-full in the connection string.
  • Keep the database off the public internet: put it in a private network.
  • Store credentials in a secrets manager or environment variables, never in git.

Practice

  1. Create a role reporter that can SELECT from orders and products but not customers. Test it with SET ROLE.
  2. Add a second RLS policy so tenant 1 users can also read (not write) documents with tenant_id = 3. (Hint: policies are combined with OR; use FOR SELECT.)
PostgreSQL · editable
✎ Check your understanding

1.What's the difference between a role with LOGIN and one without?

2.In an RLS policy, what does WITH CHECK control?

3.Which code is safe from SQL injection?

← Transactions, MVCC and locking